【问题标题】:Python writing dictionary to csv and read dictionary from csvPython将字典写入csv并从csv读取字典
【发布时间】:2018-03-19 14:21:03
【问题描述】:

我正在使用 pandas 来处理数据帧。我创建了一个数据框,其行如下:[id, vector] 其中 id 是字符串类型,vector 是字典类型。

现在当我将其写入 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 吗?
  • 是的。我也很高兴看到一个 json 解决方案,很高兴听到您的建议

标签: python pandas csv dictionary


【解决方案1】:

我认为您可以使用json 更好的结构作为csv 来保存dicts

对于写入使用to_json 和对于带有参数orient='records' 的读取read_json,感谢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')

【讨论】:

  • 我认为orient='records' 可能更合适,因为生成的json 只有idvector 键。
  • @EranMoshe - 对我来说效果很好,我的解决方案的真实数据有问题吗?
  • 我用 orient='records' 和不用都检查过,两次都有效。谢谢。
  • 我也检查过,我认为如果检查 json 文件,会有不同的结构。 orient=records 的解决方案具有优势 - 更好的 json 可读性和更小的文件大小。
猜你喜欢
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2012-11-04
  • 2018-06-17
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
  • 2016-03-01
相关资源
最近更新 更多