【问题标题】:converting dictionary to dataframe column in pandas将字典转换为熊猫中的数据框列
【发布时间】:2015-11-16 16:43:16
【问题描述】:

我有一个这样的嵌套字典

  d = {1 : {'we': 26, 'is': 112},
       2 : {'tp': 26, 'fp': 91},
       3 : {'pp': 23, 'kj': 74}}

我想将其更改为数据框列,以便外部 dict 键变为行,并且其元素充当列的元素。

期望的输出:

  rows           col1      
  1      'we': 26, 'is': 112
  2      'tp': 26, 'fp': 91
  3      'pp': 23, 'kj': 74

【问题讨论】:

  • 将字典转换为json
  • 我对 Python 比较陌生。还没有用过json和pickle,但是用pandas和numpy很舒服。
  • 为什么要使用 pandas 作为这个数据结构,而不是仅仅保留原版的 python 字典?

标签: python dictionary pandas dataframe


【解决方案1】:

如果这是您的字典中的内容,则不一定会保留内部字典的键顺序。

import pandas as pd
d = {1 : {'we': 26, 'is': 112},
     2 : {'tp': 26, 'fp': 91},
     3 : {'pp': 23, 'kj': 74}}
# Replace the inner dicts with their string representations
for i in d:
    d[i] = str(d[i])
# Convert to dataframe
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
# Clean up column names
df.rename(columns={'index': 'row', 0: 'col1'}, inplace=True)

【讨论】:

  • 这个方法也可以应用于列表吗?
  • @PrashantSharma 你当然可以从列表中创建一个数据框,但我没有足够的上下文来解释,如果需要,请用示例/代码创建一个新问题
  • 我也成功地用 list 做到了。非常感谢您的回复!
猜你喜欢
  • 2019-07-18
  • 2017-12-12
  • 2018-11-25
  • 1970-01-01
  • 2018-07-14
  • 2019-05-07
  • 2016-09-06
  • 2017-10-02
相关资源
最近更新 更多