【问题标题】:Reading a pickled file, unequal length error in pandas dataframe读取腌制文件,熊猫数据框中的长度不等错误
【发布时间】:2018-06-20 17:16:22
【问题描述】:

我想在 python 3.5 中读取一个泡菜文件。我正在使用以下代码。

以下是我的输出,我想将其加载为 pandas 数据框。

当我尝试使用 df = pd.DataFrame(df) 转换为 pd Dataframe 时,出现以下错误。

ValueError: arrays must all be same length

链接到数据-https://drive.google.com/file/d/1lSFBPLbUCluWfPjzolUZKmD98yelTSXt/view?usp=sharing

【问题讨论】:

标签: python-3.x pandas dataframe pickle data-science


【解决方案1】:

我认为你需要dict comprehensionconcat

from pandas.io.json import json_normalize,
import pickle

fh = open("imdbnames40.pkl", 'rb')
d = pickle.load(fh)
df = pd.concat({k:json_normalize(v, 'scores', ['best']) for k,v in d.items()})
print (df.head())

                         ethnicity score              best
'Aina Rapoza 0               Asian  0.89             Asian
             1      GreaterAfrican  0.05             Asian
             2     GreaterEuropean  0.06             Asian
             3  IndianSubContinent  0.11  GreaterEastAsian
             4    GreaterEastAsian  0.89  GreaterEastAsian

那么如果需要MultiIndex第一级的列:

df = df.reset_index(level=1, drop=True).rename_axis('names').reset_index()

【讨论】:

  • 谢谢,你是最棒的。我还阅读了您的许多其他答案。
猜你喜欢
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 2018-07-14
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
相关资源
最近更新 更多