Stack Overflow Asked by sanane sanane on December 10, 2020
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)
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
Correct answer by Patrick Artner on December 10, 2020
this works
kd = pd.DataFrame(data)
kd["col_name"]=[21, 23, 24, 21]
for this u need to make sure that the length of list is equal to number of rows. if some rows are empty u need to do this
kd["col_name"]=[21,None, 23, 24,None, 21]
for entering information in desired row and column u can do this as below
kd.loc["index_name","col_name"]=value
Answered by navaneeth nanda on December 10, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP