将新列插入数据帧可'ValueError: Length of values (4) does not match length of index (6)'



我用pandas库创建了一个数据帧。我想在数据帧中添加一列。然而,我得到了以下错误。但我认为我必须输入与行数一样多的数据。如何在所需的行和列中输入信息?如何在不输入数据的情况下创建列?

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

错误:

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

您的问题是插入的行太少。数据帧包含6行,在insert语句中只添加了4个值。如果添加一个包含数据的新列,它必须与当前长度相匹配:

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

您可以添加一个新的空列,如下所示:

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

或";技巧";Panda,通过列表切片给定的数据并在末尾添加足够的Nones:

# 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)

获取

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

这适用于

kd = pd.DataFrame(data) 
kd["col_name"]=[21, 23, 24, 21]

为此,u需要确保列表的长度等于行数。如果有些行是空的,你需要做这个

kd["col_name"]=[21,None, 23, 24,None, 21]

为了在所需的行和列中输入信息,u可以按照以下进行操作

kd.loc["index_name","col_name"]=value

最新更新