在pandas中向现有数据框添加新行时出错

pyc*_*yco 8 python data-analysis dataframe pandas

嗨,我有以下数据帧.

df3=pd.DataFrame(columns=["Devices","months"])
Run Code Online (Sandbox Code Playgroud)

我从循环行获取行值,打印(数据)

    Devices     months
1  Powerbank  Feb month
Run Code Online (Sandbox Code Playgroud)

当我将此数据行添加到我的df3时,我收到错误.

  df3.loc[len(df3)]=data
Run Code Online (Sandbox Code Playgroud)

muo*_*uon 12

使用

df3 = pd.concat([df3, data], axis=0)
Run Code Online (Sandbox Code Playgroud)

或者按照@Wen的建议使用

df3 = df3.append(data)
Run Code Online (Sandbox Code Playgroud)


Joa*_*MVR 10

来自https://pandas.pydata.org/pandas-docs/stable/merging.html:

但值得注意的是,concat(因此追加)会生成数据的完整副本,并且不断重用此函数可能会产生重大的性能损失.如果需要对多个数据集使用该操作,请使用列表推导.

您应该使用loc,就像您尝试做的那样,并使用字典,其中键是列名称,值是要添加的行的数据.

import pandas as pd

df3 = pd.DataFrame(columns=["Devices","months"])
new_entry = {'Devices': 'device1', 'months': 'month1'}

df3.loc[len(df3)] = new_entry
Run Code Online (Sandbox Code Playgroud)