我有一组带有相同键的字典,并且我已经有了一个带有df标头的pandas模板。我需要遍历数组并将每个字典附加到df。
arr_dics = [{'event':'alpha', 'site':'beta', 'date':'gamma'}, {'event':'a', 'site':'b', 'date':'c'}]
for i in range(len(arr_dics)):
new_dic = arr_dics[i]
two_games_df.append(new_dic, ignore_index=True)
但是我得到的输出仅将第二个字典附加到数据帧。 我需要在某处指定索引吗?
答案 0 :(得分:2)
请注意,append
不是inplace
。因此,您需要将append
函数的输出分配给原始的df
:
two_games_df= two_games_df.append(new_dic, ignore_index=True)
答案 1 :(得分:1)
使用pd.concat
arr_dic = [{'event':'alpha', 'site':'beta', 'date':'gamma'}, {'event':'a', 'site':'b', 'date':'c'}]
df = pd.DataFrame(columns=['event','site','date'])
df = pd.concat([df, pd.DataFrame(arr_dic)])
df
event site date
0 alpha beta gamma
1 a b c
答案 2 :(得分:1)
使用
two_games_df=two_games_df.append(new_dic, ignore_index=True)
df.append将其他行添加到调用方的末尾,返回一个新对象,您需要保存新对象。
df.append不会修改原始对象。