更新时间:2022-03-23 04:01:22
Just to expand on nitin's answer set_index
:
In [100]:
df.set_index('head0')
Out[100]:
head1 head2 head3
head0
bar 32 3 100
bix 22 NaN NaN
foo 11 1 NaN
qux NaN 10 NaN
xoo NaN 2 20
请注意,这将返回df,因此您必须像df = df.set_index('head0')
那样分配回df或设置参数inplace=True
:df.set_index('head0', inplace=True)
Note that this returns the df, so you either have to assign back to the df like: df = df.set_index('head0')
or set param inplace=True
: df.set_index('head0', inplace=True)
您也可以直接分配给索引:
You can also directly assign to the index:
In [99]:
df.index = df['head0']
df
Out[99]:
head0 head1 head2 head3
head0
bar bar 32 3 100
bix bix 22 NaN NaN
foo foo 11 1 NaN
qux qux NaN 10 NaN
xoo xoo NaN 2 20
请注意,执行上述操作将需要删除多余的"head0"列,这可以通过调用
Note that doing the above will require you to drop the extraneous 'head0' column which can be done by calling drop
like so: df.drop('head0', axis=1)