Python 在熊猫中使用set_索引时出现异常
我正在Pandas中尝试set_index()方法,但我遇到一个无法解释的异常:Python 在熊猫中使用set_索引时出现异常,python,pandas,indexing,Python,Pandas,Indexing,我正在Pandas中尝试set_index()方法,但我遇到一个无法解释的异常: df movieId title genres 1 2 Jumanji (1995) Adventure|Children|Fantasy 5 6 Heat (1995) Action|Crime|Thriller 10 11 American President, The (1995) Comedy|Drama|Romance df.set_index(['a'
df
movieId title genres
1 2 Jumanji (1995) Adventure|Children|Fantasy
5 6 Heat (1995) Action|Crime|Thriller
10 11 American President, The (1995) Comedy|Drama|Romance
df.set_index(['a' , 'b' , 'c'], inplace = True)
df
KeyError: 'a'
如果要通过嵌套的
列表
(双[]
)设置索引,其长度与df相同:
df.set_index([['a' , 'b' , 'c']], inplace = True)
print (df)
movieId title genres
a 2 Jumanji (1995) Adventure|Children|Fantasy
b 6 Heat (1995) Action|Crime|Thriller
c 11 American President The (1995) Comedy|Drama|Romance
如果使用list
([]
),请尝试将列a、b、c
设置为MultiIndex
,因为不存在错误
因此,如果要按列设置索引:
df.set_index(['movieId' , 'title'], inplace = True)
print (df)
genres
movieId title
2 Jumanji (1995) Adventure|Children|Fantasy
6 Heat (1995) Action|Crime|Thriller
11 American President The (1995) Comedy|Drama|Romance