最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

aggfunc where I calculate mean by index first and then sum by column in python pivot table - Stack Overflow

matteradmin5PV0评论

I have a dataframe in Python like this and I need to build a pivot table that as aggfunc first calculates the mean of each column for each label and then sum all the mean values by column.

Dear community, any idea about how I could do that? I was thinking at 2 sequential pivot tables but this doesn't sound efficient. thanks !

the result should be something like:

I have a dataframe in Python like this and I need to build a pivot table that as aggfunc first calculates the mean of each column for each label and then sum all the mean values by column.

Dear community, any idea about how I could do that? I was thinking at 2 sequential pivot tables but this doesn't sound efficient. thanks !

the result should be something like:

Share Improve this question asked Nov 18, 2024 at 19:51 Nic_barNic_bar 313 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 1

You shouldn't put data as an image. But here is the code you should use,

df = pd.DataFrame(data)

#  Calculate the mean for each label
mean_df = df.groupby("label").mean()

# Sum the mean values across the columns
totals = mean_df.sum()

# Display the result
result = pd.DataFrame([totals], index=["tot (mean a + mean b)"])
print(result)
Post a comment

comment list (0)

  1. No comments so far