简体   繁体   中英

Rename several unnamed columns in a pandas dataframe

I imported a csv as a dataframe from San Francisco Salaries database from Kaggle

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

I created a dataframe as an aggregate function from 'df'

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

Problem 1: The first and second column appear as nameless and that shouldn't happen.

在此处输入图片说明

Even when I use code of

df2.columns

It only names TotalPay as a column

Problem 2: I try to rename, for instance, the first column as JobTitle and the code doesn't do anything

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

So the solution that was given here does not apparently work: Rename unnamed column 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

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. Pandas isn't recognising that JobTitle and Year are meant to be column headers. Pandas read_csv() is very flexible with what it will let you do.
If you import the data properly, you won't need to reindex, or relabel.

Quoting answer by MaxU:

df3 = df2.reset_index()

Thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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