我正在使用 pandas 来处理数据帧。我创建了一个数据框,其行如下:[id, vector]
其中id是字符串类型,向量是字典类型。
现在,当我将其写入 csv 文件时,该行看起来像这样(在 csv 文件中):
25377bc2-d3b6-4699-a466-6b9f544e8ba3 {u'sport>sports event>world championship': 0.5058, u'sport>sports event': 0.7032, u'sport>soccer': 0.6377, u'lifestyle and leisure>game': 0.4673, u'sport>sports event>world cup': 0.6614, u'sport>sports event>international tournament': 0.454, u'sport>sports event>national tournament': 0.541, u'sport': 0.9069, u'sport>sports organisations>international federation': 0.5046, u'sport>sports organisations': 0.6982}
我尝试将其从 csv 读回 pandas 数据帧,但是当我查看曾经是 dict
的向量类型时现在是<type 'str'>
我知道我可以用 pickle 解决它,并将 pandas 数据帧保存到 pickle 文件中。但是有没有办法正确读取csv(其中的向量是字典类型)
最佳答案
我认为你可以使用json
更好的结构作为csv
来保存dicts
。
用于写入用途to_json
并供阅读 read_json
带参数 orient='records'
,谢谢 piRSquared评论:
df = pd.DataFrame({'vector':[{'a':1, 'b':3}, {'a':4, 'b':6}], 'ID':[2,3]})
print (df)
ID vector
0 2 {'b': 3, 'a': 1}
1 3 {'b': 6, 'a': 4}
df.to_json('file.json', orient='records')
ID vector
0 2 {'b': 3, 'a': 1}
1 3 {'b': 6, 'a': 4}
df = pd.read_json('file.json', orient='records')
print (df)
print (df.applymap(type))
ID vector
0 <class 'int'> <class 'dict'>
1 <class 'int'> <class 'dict'>
编辑1:
如果需要相同的列顺序,索引值使用:
df.to_json('file.json', orient='split')
df = pd.read_json('file.json', orient='split')
关于Python 将字典写入 csv 并从 csv 读取字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46628403/