如何修复:值错误所有数组的长度必须相同

799 阅读2分钟

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

ValueError: All arrays must be of the same length

当你试图创建一个pandas DataFrame,而不是DataFrame中的每一列都有相同的长度时,这个错误就会发生。

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

如何重现该错误

假设我们试图创建下面这个pandas DataFrame:

import pandas as pd

#define arrays to use as columns in DataFrame
team = ['A', 'A', 'A', 'A', 'B', 'B', 'B']
position = ['G', 'G', 'F', 'F', 'G', 'G', 'F', 'F']
points = [5, 7, 7, 9, 12, 9, 9, 4]

#attempt to create DataFrame from arrays
df = pd.DataFrame({'team': team,
                   'position': position,
                   'points': points})

ValueError: All arrays must be of the same length

我们收到一个错误,告诉我们每个数组没有相同的长度。

我们可以通过打印每个数组的长度来验证这一点:

#print length of each array
print(len(team), len(position), len(points))

7 8 8

我们看到 "团队 "数组只有7个元素,而 "位置 "和 "点数 "数组各有8个元素。

如何修复该错误

解决这个错误的最简单的方法是确保我们使用的每个数组都有相同的长度:

import pandas as pd

#define arrays to use as columns in DataFrame
team = ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B']
position = ['G', 'G', 'F', 'F', 'G', 'G', 'F', 'F']
points = [5, 7, 7, 9, 12, 9, 9, 4]

#create DataFrame from arrays
df = pd.DataFrame({'team': team,
                   'position': position,
                   'points': points})

#view DataFrame
df

	team	position points
0	A	G	 5
1	A	G	 7
2	A	F	 7
3	A	F	 9
4	B	G	 12
5	B	G	 9
6	B	F	 9
7	B	F	 4

注意,这次每个数组的长度都是一样的。

这样,当我们使用数组来创建pandas DataFrame时,我们就不会收到错误,因为每一列都有相同的长度。

其他资源

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

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