在一个个人项目中,我使用了一个数据框并得到了类似的东西
In[1] :
from random import random
companies = ['Google', 'Apple', 'Nike', 'Microsoft']
Years = [2020, 2019, 2018]
df = pd.DataFrame(columns=['Company', 'Year', 'Money'])
iterator = 0
for company in companies:
for year in Years:
df.loc[iterator] = [company, year, random()]
iterator += 1
df.set_index('Year').pivot(columns='Company', values='Money')
Out[1]:
Company Apple Google Microsoft Nike
Year
2018 0.290925 0.568462 0.459147 0.755947
2019 0.919250 0.529112 0.881319 0.700846
2020 0.064253 0.742629 0.232048 0.522739
我想乘坐Company
和Year
,这样我的输出就变成了
Out[2]:
Apple Google Microsoft Nike
2018 0.290925 0.568462 0.459147 0.755947
2019 0.919250 0.529112 0.881319 0.700846
2020 0.064253 0.742629 0.232048 0.522739
我知道可以像这样删除原始索引名称:
del df.index.name
但是如何删除列索引名称?
最佳答案
您可以使用以下方法执行此操作:
del df.columns.name
或同时使用
df.rename_axis(index=None, columns=None)
因此,在枢纽语句的末尾,链接 rename_axis
方法,如下所示:
df = df.set_index('Year').pivot(columns='Company', values='Money')\
.rename_axis(index=None, columns=None)
输出:
Apple Google Microsoft Nike
2018 0.491759 0.102509 0.799196 0.603748
2019 0.640801 0.966476 0.401801 0.928443
2020 0.678182 0.373457 0.524619 0.389381
关于python - 如何删除行和列的索引名称? (轴=0 & 轴=1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57314758/