Getting error when adding a new row to my existing dataframe in pandas

[亡魂溺海] 提交于 2021-01-27 02:51:32

问题


I have the below data frame.

df3=pd.DataFrame(columns=["Devices","months"])

I am getting row value from a loop row, print(data)

    Devices     months
1  Powerbank  Feb month

When I am adding this data row to my df3 I am getting an error.

  df3.loc[len(df3)]=data

ValueError: cannot set a row with mismatched columns


回答1:


use

df3 = pd.concat([df3, data], axis=0)

or as suggested by @Wen use

df3 = df3.append(data)



回答2:


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

It is worth noting however, that concat (and therefore append) makes a full copy of the data, and that constantly reusing this function can create a significant performance hit. If you need to use the operation over several datasets, use a list comprehension.

You should use loc, like you were trying to do, and with a dictionary where the keys are the column names and the values are the data of the row being added.

import pandas as pd

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

df3.loc[len(df3)] = new_entry



回答3:


If someone is looking to append new row which is in dictionary format, below will help.

  • Existing DataFrame
In [6]: df
Out[6]: 
     Devices     months
0  Powerbank  Feb month

In [7]:
  • Below snippet adds another row to existing 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]:

Hope that helps.




回答4:


As the error suggests the number of columns should of the data being inserted into the dataframe must match the number of columns of the 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


来源:https://stackoverflow.com/questions/45104991/getting-error-when-adding-a-new-row-to-my-existing-dataframe-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!