如何修复:值的长度与索引的长度不一致

6,581 阅读2分钟

在使用pandas时,你可能会遇到的一个错误是:

ValueError: Length of values does not match length of index

当你试图将一个NumPy数组的值分配给pandas DataFrame中的一个新列,然而该数组的长度与当前的索引长度不匹配时,就会发生这个错误。

下面的例子展示了如何在实践中解决这个错误。

如何重现这个错误

假设我们有下面这个pandas DataFrame:

import pandas as pd

#define DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14],
                   'assists': [5, 7, 13, 12]})

#view DataFrame
print(df)

   points  assists
0      25        5
1      12        7
2      15       13
3      14       12

现在假设我们试图以NumPy数组的形式添加一个名为 "rebounds "的新列:

import numpy as np

#attempt to add 'rebounds' column
df['rebounds'] = np.array([3, 3, 7])

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

我们收到一个ValueError,因为我们试图将一个长度为3的NumPy数组添加到一个索引长度为4的DataFrame中。

如何修复该错误

解决这个错误的最简单的方法是使用pandas Series而不是NumPy数组来创建一个新列。

默认情况下,如果pandas系列的长度与DataFrame的索引长度不一致,那么NaN值将被填入:

#create 'rebounds' column
df['rebounds'] = pd.Series([3, 3, 7])

#view updated DataFrame
df

	points	assists	rebounds
0	25	5	3.0
1	12	7	3.0
2	15	13	7.0
3	14	12	NaN

使用pandas系列,我们能够成功地添加 "篮板 "列,缺失的值将被简单地填入NaN。

请注意,我们可以使用如下的**fillna()**方法将NaN值快速转换为其他值(如0):

#fill in NaN values with zero
df = df.fillna(0)

#view updated DataFrame
df

points	assists	rebounds
0	25	5	3.0
1	12	7	3.0
2	15	13	7.0
3	14	12	0.0

请注意,NaN值已被转换为零。

其他资源

下面的教程解释了如何修复Python中的其他常见错误:

如何修复Pandas中的KeyError
如何修复。ValueError: 无法将浮点数NaN转换为整数
如何修复。ValueError:操作数不能与形状一起广播