[英]Calculating column means based on values in other columns in pandas
I have a pandas dataframe laid out like the following:我有一个 pandas dataframe 布局如下:
[Name_Date] [Var_A] [Var_1] [Var_2] ...
FooBar_09/2021 9 1 9
FooBar_09/2021 5 2 8
FooBar_09/2021 3 5 6
BarFoo_03/2020 8 3 2
BarFoo_03/2020 3 4 4 ...
BarFoo_03/2020 4 3 6
BarBar_04/2017 3 1 5
BarBar_04/2017 7 1 3
BarBar_04/2017 1 3 1 ...
I'd like to create a new dataframe with unique values from [Name_Date], and the mean values from [Var_A] based on the groups in [Name_Date].我想创建一个新的 dataframe,其具有来自 [Name_Date] 的唯一值,以及基于 [Name_Date] 中的组的来自 [Var_A] 的平均值。 I've gotten this far with the following line:我已经通过以下行做到了这一点:
df_mean = df.groupby('Name_Date', as_index=False)['Var_A'].mean()
What I'd like to do is then expand on this by calculating the mean of columns [Var1] and [Var2], and dividing them by the mean of [Var_A].然后我想做的是通过计算列 [Var1] 和 [Var2] 的平均值并将它们除以 [Var_A] 的平均值来扩展这一点。 I am sure I could do this calculation one by one in a similar fashion to the line above, however I have about a dozen of these [Var] columns so I'm looking for a more expiditious way to do this if anyone can make any suggestions.我确信我可以以与上一行类似的方式逐一进行此计算,但是我有大约十几个这样的 [Var] 列,因此如果有人可以进行任何操作,我正在寻找一种更快捷的方法来执行此操作建议。 The end result I'm trying to achieve can be seen below:我试图达到的最终结果如下所示:
[Name_Date] [Var_A_mean] [mean Var_A / mean Var_1] [mean Var_A / mean Var_2]
FooBar_09/2021 5.6 0.47 1.3
BarFoo_03/2020 5 0.66 0.8
BarBar_04/2017 3.6 0.46 0.83
Thanks for the help.谢谢您的帮助。
Use groupby
to compute the mean for all columns then div
on index axis:使用groupby
计算所有列的平均值,然后在索引轴上div
:
df_mean = df.groupby('Name_Date').mean()
df_mean.update(df_mean.iloc[:, 1:].div(df_mean['Var_A'], axis=0))
print(df_mean)
# Output:
Var_A Var_1 Var_2
Name_Date
BarBar_04/2017 3.666667 0.454545 0.818182
BarFoo_03/2020 5.000000 0.666667 0.800000
FooBar_09/2021 5.666667 0.470588 1.352941
You can simply get the mean of all 3 columns, then calculate the div and rename them:您可以简单地获取所有 3 列的平均值,然后计算 div 并重命名它们:
PS, by the result numbers it seems like it's Var_1 / Var_A
and Var_2 / Var_A
, which is different from the names you provided PS,根据结果编号,它似乎是Var_1 / Var_A
和Var_2 / Var_A
,这与您提供的名称不同
df_mean = df.groupby('Name_Date', as_index=False)[['Var_A', 'Var_1', 'Var_2']].mean()
df_mean['Var_1'] = df_mean['Var_1']/df_mean['Var_A']
df_mean['Var_2'] = df_mean['Var_2']/df_mean['Var_A']
df_mean.columns = ['Name_Date', 'Var_A_mean','mean Var_A / mean Var_1', 'mean Var_A / mean Var_2']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.