Reputation: 167
I am trying to export this DF into my desired output:
import pandas as pd
data = {'V': ["0","0","0","0","0","0"],
'A': ["1","0","1","1","1","0"],
}
df = pd.DataFrame (data, columns = ['V','A'])
Desired Output:
{"0": {"V": 0,
"A": 1,
},
"1": {"V": 0,
"A": 0,
},
...
}
Exporting it as json doesn't have the same form.
df= df.to_json(orient="table")
with open('df.json', 'w') as f:
f.write(df)
Upvotes: 0
Views: 87
Reputation: 34056
Use df.to_dict
with orient=index
:
In [1672]: x = df.to_dict('index')
In [1672]: x
Out[1672]:
{0: {'V': '0', 'A': '1'},
1: {'V': '0', 'A': '0'},
2: {'V': '0', 'A': '1'},
3: {'V': '0', 'A': '1'},
4: {'V': '0', 'A': '1'},
5: {'V': '0', 'A': '0'}}
For json
output:
In [1676]: import json
In [1679]: y = json.dumps(x)
In [1681]: y
Out[1681]: '{"0": {"V": "0", "A": "1"}, "1": {"V": "0", "A": "0"}, "2": {"V": "0", "A": "1"}, "3": {"V": "0", "A": "1"}, "4": {"V": "0", "A": "1"}, "5": {"V": "0", "A": "0"}}'
EDIT: To convert values into int
, do this:
In [1672]: x = df.to_dict('index')
In [1708]: x = {k: {kk: int(vv) for kk, vv in v.items()} for k, v in x.items()}
In [1710]: y = json.dumps(y)
In [1711]: y
Out[1711]: '{"0": {"V": 0, "A": 1}, "1": {"V": 0, "A": 0}, "2": {"V": 0, "A": 1}, "3": {"V": 0, "A": 1}, "4": {"V": 0, "A": 1}, "5": {"V": 0, "A": 0}}'
Upvotes: 1