0

我有一个 517 个元组的列表。当我使用该列表使用 .loc 对我的数据框进行切片时,不知何故有 518 行。如果它很重要,这些是多索引的 517 个元组。结果的视觉检查似乎没有明显的标题或空行。

print(submatrix2.shape)
x = list(get_list_of_university_towns().itertuples(index=False, name=None))
print(len(x))
univ_matrix = submatrix2.loc[x,] 
print(univ_matrix.shape)

输出:

(10730, 1)
517
(518,1)

什么可能导致这种不匹配?

4

1 回答 1

0

您可能有一个重复的索引,它允许您的最终形状大于您传递的列表。

可重现的例子:

df = pd.DataFrame({'vals':["a", "b", "c", "d"],
                   'n':[0,1,1,2]})

df = df.set_index('n')


    vals
n   
0   a
1   b
1   c
2   d

现在

>>> x=[0,1,2];len(x)
3
>>> df.loc[x,:].shape
(4, 1)
于 2018-07-10T02:26:56.623 回答