简体   繁体   中英

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.

Use rename function of the DataFrame:

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

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