首页 > 解决方案 > 如何删除行和列的索引名称?(轴=0 & 轴=1)

问题描述

在一个个人项目中,我使用了一个数据框并有类似的东西

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

但是如何删除列索引名称?

标签: pythonpandasjupyter-notebook

解决方案


只需将列和索引重命名为None

df.columns.name, df.index.name = None, None

结果

        Apple       Google      Microsoft   Nike
2018    0.385702    0.402060    0.649404    0.640924
2019    0.999002    0.869702    0.129008    0.082098
2020    0.993765    0.402157    0.902664    0.774389

推荐阅读