Steve
Steve

Reputation: 35

Unable to change a column name in a dataframe

I'm working on some survey data and am looking to graph some of the results with standard deviation.

I can successfully create the new column with the std values, but it names the column (Question 3, std). I've then tried to rename the column 'std', but the column name doesn't change.

new_df = df.groupby('Respondants')[['Question 3']].agg({'std'})
std_df = df.merge(new_df, left_on=['Respondants'], right_index=True)
col_dict = {'Question 3': 'std'} 
std_df.columns = [col_dict.get(x, x) for x in std_df.columns]

What am I missing?

EDIT: The strange thing is that I've now tried:

new_df = df.groupby('Respondants')[['Question 3']].agg({'std'})
std_df = df.merge(new_df, left_on=['Respondants'], right_index=True)
std_df.rename(columns={'(Question 3, std)': 'std'}, inplace=True)
std_df.head(200)

and the result is the same. But if I try:

new_df = df.groupby('Respondants')[['Question 3']].agg({'std'})
std_df = df.merge(new_df, left_on=['Respondants'], right_index=True)
std_df.rename(columns={'Question 1': 'whatever'}, inplace=True)
std_df.head(200)

That column name changes, so the code works, but not for the column that I needed.

Upvotes: 1

Views: 167

Answers (1)

RaJa
RaJa

Reputation: 1567

Use rename function of the DataFrame:

std_df.rename(columns={'(Question 3, std)': 'std'}, inplace=True)

Upvotes: 1

Related Questions