Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a new column into a dataframes gives 'ValueError: Length of values (4) does not match length of index (6)'

I created a dataframe with the pandas library. I want to add a column to the dataframe. However I am getting the following error.But I think I have to enter as much data as the number of lines.How can I enter information in the row and column I want? How can I create a column without entering data?

import pandas as pd

kd = pd.DataFrame(data) 
insertColumns = kd.insert(0, "Age", [21, 23, 24, 21],True ) 
print(kd)

error:

ValueError: Length of values (4) does not match length of index (6)

1 Answers

Your problem is that you insert too few rows. Your dataframe contains 6 rows, you only add 4 values in your insert statement. If you add a new column with data, it has to match the current length:

import pandas as pd

df = pd.DataFrame({"1":list(range(6))})
df.insert(0, "Age", [21, 23, 24, 21],True )
# Length of values does not match length of index

You can add a new empty column like so:

df["new_col"] = None

# or

df.insert(0,"Age", None, True)  # to get a new colum at position 0 all None

or "trick" pandas by list slicing the given data and append enough Nones at end:

# extend the data you want to give by a None-List and slice the whole down to size
df.insert(0,"Age", ([21,23,24,21] + [None]*len(df))[:len(df)], True)

to get

    Age  1
0  21.0  0
1  23.0  1
2  24.0  2
3  21.0  3
4   NaN  4   # only 2 None appends needed 
5   NaN  5
like image 147
Patrick Artner Avatar answered Dec 11 '25 19:12

Patrick Artner