Python中DataFrame行重命名失败求助:均值计算后无法修改索引名
Hey there! Let's break down why your rename attempt isn't working and fix it right away—you're just a couple of small adjustments away from getting what you want.
The Core Issue
First off, when you run df10.mean(), you're getting a Pandas Series (not a DataFrame) as your output. Series don't have "columns"—they have an index (the labels you're calling "行名"). That's why using the columns parameter in rename() does nothing here.
On top of that, Python's boolean values are case-sensitive: you need True (uppercase T) instead of true. And if you use inplace=True, the method modifies the original object directly and returns None, so assigning it to a new variable is unnecessary.
Corrected Code Options
Option 1: Create a New Renamed Series (Recommended)
This keeps your original data intact and gives you a new Series with the updated labels:
# Define your label mapping new_labels = { '1-': 'EVC -', '1+': 'EVC +', '2-': 'RBS* mVenus -', '2+': 'RBS* mVenus +', '3-': 'H56-1 mVenus -', '3+': 'H56-1 mVenus +', '4-': 'H56-1 mVenus + T56-0 -', '4+': 'H56-1 mVenus + T56-0 +', '5-': 'H56-2 mVenus -', '5+': 'H56-2 mVenus +', '6-': 'H56-2 mVenus + T56-0 -', '6+': 'H56-2 + T56-0 +', '7-': 'RBS* mVenus T56-0 -', '7+': 'RBS* mVenus T56-0 +' } # Rename the Series index df10mean_renamed = df10mean.rename(new_labels)
Option 2: Modify the Original Series In-Place
If you want to update the original Series directly:
new_labels = { '1-': 'EVC -', '1+': 'EVC +', '2-': 'RBS* mVenus -', '2+': 'RBS* mVenus +', '3-': 'H56-1 mVenus -', '3+': 'H56-1 mVenus +', '4-': 'H56-1 mVenus + T56-0 -', '4+': 'H56-1 mVenus + T56-0 +', '5-': 'H56-2 mVenus -', '5+': 'H56-2 mVenus +', '6-': 'H56-2 mVenus + T56-0 -', '6+': 'H56-2 + T56-0 +', '7-': 'RBS* mVenus T56-0 -', '7+': 'RBS* mVenus T56-0 +' } # Update the index directly on the original Series df10mean.rename(new_labels, inplace=True) # Note: No need to assign to a new variable here—df10mean is already modified
Bonus: Convert to DataFrame (If Needed)
If you later want to turn this renamed Series into a DataFrame, you can use:
df_renamed = df10mean_renamed.to_frame(name='Mean Values')
内容的提问来源于stack exchange,提问作者Wasabinuss




