PYTHON 初学者:如何从 python 字典列表中创建 pandas 数据框?

PYTHON BEGUINNER : How to create pandas dataframe from a list of python dictionaries?

我正在寻找一种创建 pandas DataFrame 的方法,然后使用字典列表中的 pandas 将其添加到 excel 文件中。

第一个字典有 3 个值(整数),第二个字典有一个值对应一组单词。两个字典的键是相同的,但为了确保 excel 文件中没有错误,我更喜欢将它们放在 DataFrame 中。

d1 = {'1': ['45', '89', '96'], '2': ['78956', '50000', '100000'], '3': ['0', '809', '656']}
d2 = {'1': ['connaître', 'rien', 'trouver', 'être', 'emmerder', 'rien', 'suffire', 'mettre', 'multiprise'], '2': ['trouver', 'être', 'emmerder'], '3' : ['con', 'ri', 'trou', 'êt', 'emmer',]}

我在每次试探时都遇到错误,我真的很困惑,我需要一个解决方案


df = pd.read_csv(sys.argv[1], na_values=['no info', '.'], encoding='Cp1252', delimiter=';')
df1 = pd.DataFrame(d1).T.reset_index()
df1['value1_d2'] = ''
# iterate over the dict and add the lists of words in the new column
for k,v in d2.items():
    df1.at[int(k) - 1, 'value1_d2'] = v 
#print(df1)
df1.columns = ['id','value_1_Dict1','value_2_Dict1','value_3_Dict1',' value_2_Dict2']
cols = df1.columns.tolist()
cols = cols[-1:] + cols[:-1]
df1 = df1[cols]
print(df1)
df = pd.concat([df, df1], axis = 1)
df.to_excel('exit.xlsx')


我没有错误,但数据框的填充在示例中的真实列之后开始,我有超过 2000 行

预期输出:我将其添加到现有文件中:

  score  freq    **value1_d2                       id value1   value2 value3  **    
0  0.5     2     **['connaître', 'rien', 'trouver'] 1  45       89       96   **
1  0.8     5     ** ['trouver', 'être', 'emmerder'] 2  78956    5000    100000 **   
2  0.1     5     **['con', 'ri', 'trou', 'êt', 'emmer',] 3  0        809     65  **


当尝试添加到 excel 文件时出现以下错误,我想从第一列开始写入以便密钥相同。

有没有办法使用 pandas 解决它(我必须使用 pandas 来参加这个研讨会。

谢谢。

这样您就可以在单元格中添加单词列表:

df1 = pd.DataFrame(d1)

# the new column needs to have dtype object
df1['value1_d2'] = ''

# iterate over the dict and add the lists of words in the new column
for k,v in d2.items():
    df1.at[int(k) - 1, 'value1_d2'] = v

我也使用了 this post 中的信息。

将字典读入数据框时,您可以使用:

>>> d1 = {'1': ['45', '89', '96'], '2': ['78956', '50000', '100000'], '3': ['0', '809', '656']}
>>> df1 = pd.DataFrame.from_dict(d1)