Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字典转换为pandas中的dataframe列_Python_Dictionary_Pandas_Dataframe - Fatal编程技术网

Python 将字典转换为pandas中的dataframe列

Python 将字典转换为pandas中的dataframe列,python,dictionary,pandas,dataframe,Python,Dictionary,Pandas,Dataframe,我有一本这样的嵌套字典 d = {1 : {'we': 26, 'is': 112}, 2 : {'tp': 26, 'fp': 91}, 3 : {'pp': 23, 'kj': 74}} 我想将其更改为dataframe列,以便外部dict键成为行,其元素充当列的元素 期望输出: rows col1 1 'we': 26, 'is': 112 2 'tp': 26, 'fp': 91 3

我有一本这样的嵌套字典

  d = {1 : {'we': 26, 'is': 112},
       2 : {'tp': 26, 'fp': 91},
       3 : {'pp': 23, 'kj': 74}}
我想将其更改为dataframe列,以便外部dict键成为行,其元素充当列的元素

期望输出:

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

如果这就是你字典中的内容,那么它不一定会保留内部dict的键顺序

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)

如果这就是你字典中的内容,那么它不一定会保留内部dict的键顺序

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)

将dict转换为jsonI对于Python来说是相当新的。我还没有使用json和pickle,但是对pandas和numpy很熟悉。为什么要在这个数据结构中使用pandas,而不仅仅是保留普通的python dict呢?将dict转换成jsonI我对python还是比较陌生的。我还没有使用json和pickle,但对pandas和numpy很熟悉。为什么要使用pandas作为这种数据结构,而不仅仅是保留普通的python dict?这种方法也可以应用于列表吗?@PrashantSharma你当然可以从列表创建数据框架,但我没有足够的上下文来解释,如果需要,请用示例/代码创建一个新问题我也成功地用列表创建了一个新问题。非常感谢您的回复!!这个方法也可以应用于列表吗?@PrashantSharma你当然可以从列表中创建一个数据帧,但我没有足够的上下文来解释,如果需要,请创建一个带有示例/代码的新问题我也成功地使用了列表。非常感谢您的回复!!