I have the following pandas DF
JavaScript
x
7
1
data
2
day 2021-09-30
3
value1 730716000
4
value2 974689000
5
value3 375689000
6
value4 369077000
7
How can I convert this DF to json to be like:
JavaScript
1
8
1
{
2
"day": "2021-09-30",
3
"value1": 702228000,
4
"value2": 924465000,
5
"value3": 309753000,
6
"value4": 306252
7
}
8
My best try was:
JavaScript
1
3
1
df.columns = range(df.shape[1]) # Delete headers
2
print(df.to_json(orient='index', indent=2))
3
But I got this output:
JavaScript
1
18
18
1
{
2
"day":{
3
"0":"2021-09-30"
4
},
5
"value1":{
6
"0":"730716000"
7
},
8
"value2":{
9
"0":"974689000"
10
},
11
"value3":{
12
"0":"375689000"
13
},
14
"value4":{
15
"0":"369077000"
16
}
17
}
18
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
JavaScript
1
9
1
>>> print(df.squeeze().to_json(indent=4))
2
{
3
"day":"2021-09-30",
4
"value1":"730716000",
5
"value2":"974689000",
6
"value3":"375689000",
7
"value4":"369077000"
8
}
9
For the bonus, use a different strategy
JavaScript
1
15
15
1
import json
2
3
data = json.dumps({k: int(v) if v.isdigit() else v
4
for k, v in df.squeeze().to_dict().items()}, indent=2)
5
print(data)
6
7
# Output
8
{
9
"day": "2021-09-30",
10
"value1": 730716000,
11
"value2": 974689000,
12
"value3": 375689000,
13
"value4": 369077000
14
}
15