我有以下数据框。
df3=pd.DataFrame(columns=["Devices","months"])
我正在从循环中获取行值 row, 打印数据
Devices months
1 Powerbank Feb month
当我将这个数据行添加到我的df3中时,出现了错误。
df3.loc[len(df3)]=data
ValueError: 无法使用不匹配的列设置行。
我有以下数据框。
df3=pd.DataFrame(columns=["Devices","months"])
我正在从循环中获取行值 row, 打印数据
Devices months
1 Powerbank Feb month
当我将这个数据行添加到我的df3中时,出现了错误。
df3.loc[len(df3)]=data
df3 = pd.concat([df3, data], axis=0)
或者按照 @Wen 的建议使用
df3 = df3.append(data)
axis=0
是默认值,可以省略。 - VMAtmignore_index
,那么可能会出现错误。df3 = df3.append(data, ignore_index=True)
- asantz96来自https://pandas.pydata.org/pandas-docs/stable/merging.html:
需要注意的是,concat(以及因此也包括append)会完全复制数据,频繁重用此函数可能会导致显著的性能问题。如果您需要在多个数据集上使用该操作,请使用列表推导。
您应该像尝试做的那样使用loc,并使用字典,其中键是列名,值是要添加行的数据。
import pandas as pd
df3 = pd.DataFrame(columns=["Devices","months"])
new_entry = {'Devices': 'device1', 'months': 'month1'}
df3.loc[len(df3)] = new_entry
In [6]: df
Out[6]:
Devices months
0 Powerbank Feb month
In [7]:
以下代码片段向现有DataFrame中添加了另一行。
In [7]: dictionary_row = {"Devices":"Laptop","months":"Mar month"}
In [8]: df = df.append(dictionary_row, ignore_index=True)
In [9]: df
Out[9]:
Devices months
0 Powerbank Feb month
1 Laptop Mar month
In [10]:
希望能帮到你。dataframe
中的数据的列数必须与dataframe
的列数相匹配。>>> df3=pd.DataFrame(columns=["Devices","months"])
>>> df3.loc[len(df3)] = ['Powerbank','Feb']
>>> df3
Devices months
0 Powerbank Feb
>>> data = ['powerbank','feb']
>>> df3.loc[len(df3)] = data
>>> df3
Devices months
0 Powerbank Feb
1 powerbank feb
append
。 - BENY