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

Viewed 34681

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

4 Answers

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.

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
Related