Reputation: 11161
When I save a pandas.DataFrame
to a .csv
file, a column of dicts
is converted to literal strings. How can I save/load a df to .csv
so that they are equivalent? I know about pickle, hdf5, etc; I'd like to keep it human readable, but I'm open to alternatives if this is barking up the wrong tree...
df = pd.DataFrame.from_items([('A', [1, 2, {3:30}]), ('B', [4, 5, {6:60}])],
orient='index', columns=['one', 'two', 'three'])
df.to_csv('test.csv', sep='\t')
df_loaded = pd.read_csv('test.csv', sep='\t', index_col=0)
df == df_loaded
"""
output:
one two three
A True True False
B True True False
"""
Upvotes: 1
Views: 954
Reputation: 49774
Try pandas.DataFrame.to_json()
:
import pandas as pd
df = pd.DataFrame.from_items(
[('A', [1, 2, {3: 30}]), ('B', [4, 5, {6: 60}])],
orient='index', columns=['one', 'two', 'three'])
df.to_json('test.csv')
print(pd.read_json('test.csv'))
one three two
A 1 {'3': 30} 2
B 4 {'6': 60} 5
Upvotes: 2