将df保存并检索为.csv,而不会丢失类型信息

时间:2018-02-16 03:16:09

标签: python pandas csv file-io

当我将pandas.DataFrame保存到.csv文件时,dicts列将转换为文字字符串。如何将df保存/加载到.csv以使它们等效?我知道泡菜,hdf5等;我想保持它的可读性,但如果这是在错误的树上咆哮,我愿意接受替代方案......

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
"""

1 个答案:

答案 0 :(得分:2)

尝试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