0

I have pandas groupby object

| A  | B | C |
|----|---|---|
| a1 | 3 | 4 |
| a2 | 6 | 2 |

And I want to add new column which will have average in row format

Required Output

| A  | B | C | Average |
|----|---|---|---------|
| a1 | 3 | 4 | 3.5     |
| a2 | 6 | 2 | 4       |

I tried

df.columns = df.columns.add_categories(['Average'])
df['Average'] = df.mean(axis = 1)

But this gives me

AttributeError: 'Index' object has no attribute 'add_categories'

1 Answer 1

2

If there is no catogoricals in columns names only use mean:

df['Average'] = df.mean(axis = 1)

Or if want convert columns names to CategoricalIndex then use:

df.columns = pd.CategoricalIndex(df.columns)
df.columns = df.columns.add_categories(['Average'])
df['Average'] = df.mean(axis = 1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.