【问题标题】:Removing dataframe row names in Python Pandas在 Python Pandas 中删除数据框行名
【发布时间】:2020-10-18 09:20:44
【问题描述】:

我在 Pandas 中有这样的数据框:

# https://www.datasciencemadesimple.com/reshape-long-wide-pandas-python-pivot-function/
import pandas as pd
import numpy as np 

from platform import python_version
print(python_version()) #3.7.7

#Create a DataFrame

d = {'countries':['A','B','C','A','B','C'],
     'continent': ['Europe', 'Asia','Africa', 'Europe', 'Asia','Africa'],
'metrics':['population_in_million','population_in_million','population_in_million',
'gdp_percapita','gdp_percapita','gdp_percapita'],
'values':[100,200,120,2000,7000,15000] }

df = pd.DataFrame(d,columns=['countries','continent','metrics','values'])
df

我使用以下代码将其转换为宽数据框:

# https://stackoverflow.com/questions/47178861/pandas-long-to-wide-format-with-multi-index
test_df = pd.DataFrame(df.pivot_table(index=['countries', 'continent'], columns='metrics', values='values'))

test_df = test_df.reset_index() 
test_df

我正在寻找一种删除“指标”的方法。以前的答案没有帮助。我的 Python 版本是 3.7.7

【问题讨论】:

  • 你可以做test_df.rename_axis(None, axis=1)

标签: python pandas data-wrangling


【解决方案1】:

您应该可以通过删除“列”的名称来做到这一点,即

test_df.columns.name = None

或者,使用内置的 Pandas 方法:

test_df.rename_axis(mapper=None, axis=1, inplace=True)

mapper是你想设置名字的值,axis是1因为你在看列名,如果你想替换当前的名字也可以指定inplace=True重新分配。

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2022-12-06
    • 2020-02-24
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多