2024-03-29 11:37:48 发布
网友
我有这个DF
print(df) head0 head1 head2 head3 0 bar 32 3 100 1 bix 22 NaN NaN 2 foo 11 1 NaN 3 qux NaN 10 NaN 4 xoo NaN 2 20
我要做的是使用head0作为行名:
head0
head1 head2 head3 bar 32 3 100 bix 22 NaN NaN foo 11 1 NaN qux NaN 10 NaN xoo NaN 2 20
我怎样才能做到?
您可以对数据帧使用set_index方法,如下所示
df.set_index(df.head0)
只是为了进一步解释尼廷的回答^{}:
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 = df.set_index('head0'),要么设置参数inplace=True:df.set_index('head0', inplace=True)
df = df.set_index('head0')
inplace=True
df.set_index('head0', inplace=True)
也可以直接分配给索引:
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”列,可以通过调用^{}来完成,例如:df.drop('head0', axis=1)
df.drop('head0', axis=1)
您可以对数据帧使用set_index方法,如下所示
只是为了进一步解释尼廷的回答^{} :
请注意,这将返回df,因此您要么像这样分配给df:
df = df.set_index('head0')
,要么设置参数inplace=True
:df.set_index('head0', inplace=True)
也可以直接分配给索引:
请注意,执行上述操作将要求您删除无关的“head0”列,可以通过调用^{} 来完成,例如:
df.drop('head0', axis=1)
相关问题 更多 >
编程相关推荐