Home > front end >  Value error while adding column with more number of values in pandas dataframe
Value error while adding column with more number of values in pandas dataframe

Time:01-12

I am trying to insert a column with more number of values in it compared to other columns and it is resulting in value error. how to avoid the error/

import pandas as pd
table5={'Roll':[1,2,3,4,5],'Name':['Nidhi','Anil','Poonam','Karambir','Sangeeta'],
        'Marks':[87,45,67,39,78]}
indexelements=['S1','S2','S3','S4','S5']
df=pd.DataFrame(table5,index=indexelements)


df.insert(1,'gender',['F','M','F','M','F','F'])

It shows:ValueError: Length of values (6) does not match length of index (5)

CodePudding user response:

The number of values in the new column must match the number of rows in the DataFrame, else pandas raises a ValueError.

Here, you are trying to insert 6 values ['F','M','F','M','F','F'] in the gender column, whereas the number of rows in the DataFrame is 5.

CodePudding user response:

Is this what you wanted?

import pandas as pd
import numpy as np


table5 = {'Roll': [1, 2, 3, 4, 5], 'Name': ['Nidhi', 'Anil', 'Poonam', 'Karambir', 'Sangeeta'],
          'Marks': [87, 45, 67, 39, 78]}
index_elements=['S1', 'S2', 'S3', 'S4', 'S5']
df=pd.DataFrame(table5, index=index_elements)
df.loc['S6'] = [np.nan, np.nan, np.nan]
print(df)

df['gender'] = ['F', 'M', 'F', 'M', 'F', 'F']
print(df)
  • Related