I have the following pandas DF
data day 2021-09-30 value1 730716000 value2 974689000 value3 375689000 value4 369077000
How can I convert this DF to json to be like:
{ "day": "2021-09-30", "value1": 702228000, "value2": 924465000, "value3": 309753000, "value4": 306252 }
My best try was:
df.columns = range(df.shape[1]) # Delete headers print(df.to_json(orient='index', indent=2))
But I got this output:
{ "day":{ "0":"2021-09-30" }, "value1":{ "0":"730716000" }, "value2":{ "0":"974689000" }, "value3":{ "0":"375689000" }, "value4":{ "0":"369077000" } }
Bonus Doubt: Is it possible to parse only the values 1,2,3 and 4 of column data to int?
Advertisement
Answer
The first approach is to squeeze
your dataframe before use to_json
>>> print(df.squeeze().to_json(indent=4)) { "day":"2021-09-30", "value1":"730716000", "value2":"974689000", "value3":"375689000", "value4":"369077000" }
For the bonus, use a different strategy
import json data = json.dumps({k: int(v) if v.isdigit() else v for k, v in df.squeeze().to_dict().items()}, indent=2) print(data) # Output { "day": "2021-09-30", "value1": 730716000, "value2": 974689000, "value3": 375689000, "value4": 369077000 }