admin管理员组

文章数量:1023230

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)

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)

本文标签: aggfunc where I calculate mean by index first and then sum by column in python pivot tableStack Overflow