简体   繁体   English

重命名Pandas数据框中的几个未命名的列

[英]Rename several unnamed columns in a pandas dataframe

I imported a csv as a dataframe from San Francisco Salaries database from Kaggle 我从Kaggle的San Francisco Salaries数据库中将csv导入为数据框

df=pd.read_csv('Salaries.csv')

I created a dataframe as an aggregate function from 'df' 我从'df'创建了一个数据框作为聚合函数

df2=df.groupby(['JobTitle','Year'])[['TotalPay']].median()

Problem 1: The first and second column appear as nameless and that shouldn't happen. 问题1:第一和第二列显示为无名,这不应该发生。

在此处输入图片说明

Even when I use code of 即使我使用

df2.columns

It only names TotalPay as a column 它仅将TotalPay命名为列

Problem 2: I try to rename, for instance, the first column as JobTitle and the code doesn't do anything 问题2:例如,我尝试将第一列重命名为JobTitle,并且代码不执行任何操作

df3=df2.rename(columns = {0:'JobTitle'},inplace=True)

So the solution that was given here does not apparently work: Rename unnamed column pandas dataframe . 因此,此处给出的解决方案显然不起作用: 重命名未命名的列pandas dataframe

I wish two possible solutions: 1) That the aggregate function respects the column naming AND/OR 2) Rename the empty dataframe's columns 我希望有两个可能的解决方案:1)聚合函数尊重列的AND / OR或2)重命名空数据框的列

The problem isn't really that you need to rename the columns. 问题并不是您真的需要重命名列。
What do the first few rows of the .csv file that you're importing look at, because you're not importing it properly. 您要导入的.csv文件的前几行会看到什么,因为您没有正确导入它。 Pandas isn't recognising that JobTitle and Year are meant to be column headers. 熊猫没有意识到JobTitleYear是列标题。 Pandas read_csv() is very flexible with what it will let you do. 熊猫read_csv()具有非常灵活的功能 ,可让您执行操作。
If you import the data properly, you won't need to reindex, or relabel. 如果正确导入数据,则无需重新索引或重新标记。

Quoting answer by MaxU: 引用MaxU的答案:

df3 = df2.reset_index()

Thank you! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM