如何为字典中的空Pandas DataFrame正确添加新行?
解决字典中空Pandas DataFrame添加新行的问题
正确操作方法
字典里的DataFrame和单独的DataFrame操作逻辑完全一致,你之前单独用的df.loc[len(df)] = row同样适用于字典中的DataFrame,直接这么写就行:
# 假设你的字典叫df_dict,要给"Maths"对应的df加行 df_dict["Maths"].loc[len(df_dict["Maths"])] = row
如果要循环多次添加,直接把这段逻辑放进循环里,每次更新row的内容即可。
为什么之前的方法出错
- 用
append(row)生成新列:因为空DataFrame没有预设列名,如果你传入的row是字典,Pandas会把字典的键当作新列名,自然生成新列而非新行。如果非要用append,需要把row转成Series并匹配原df的列名,或者用df.append(pd.DataFrame([row]), ignore_index=True),但loc的方法更高效直观。 - 触发KeyError:
Dictionary["Maths"].loc[0].append(row)的问题在于,空DataFrame根本没有索引为0的行,所以报KeyError;而且你操作的是某一行而非整个DataFrame,方向完全错了。
完整示例代码
import pandas as pd # 先创建带指定列名的空DataFrame字典(必须先定义列,否则加行容易出问题) df_dict = { "Maths": pd.DataFrame(columns=["Score", "Student"]), "English": pd.DataFrame(columns=["Score", "Student"]) } # 循环添加多行示例 rows_to_add = [ {"Score": 90, "Student": "Alice"}, {"Score": 85, "Student": "Bob"} ] for row in rows_to_add: df_dict["Maths"].loc[len(df_dict["Maths"])] = row print(df_dict["Maths"])
内容的提问来源于stack exchange,提问作者Corcky
相关产品推荐
相关产品推荐

