简体   繁体   English

Python Pandas-使用两列中的条件计算平均值

[英]Python Pandas - Calculate mean using criteria from two columns

I am trying to calculate the mean of a Pandas data frame column using selection criteria from two other columns. 我正在尝试使用其他两列中的选择条件来计算Pandas数据框列的平均值。 In the code below, there are a "Trace" and "Sample" columns that are to be used for selection criteria, while the numbers in the "Value" column are to be used in the calculation. 在下面的代码中,有一个“ Trace”和“ Sample”列将用于选择标准,而“ Value”列中的数字将在计算中使用。 I want to group by the "Trace" number and only take the average of "Sample" numbers 3, 4, and 5. Then, I would like to create a new column in the original dataframe "df" and place the calculated mean values in all of the rows corresponding to the correct "Trace" number. 我想按“跟踪”数字分组,仅取“样本”数字3、4和5的平均值。然后,我想在原始数据帧“ df”中创建一个新列,并将计算出的平均值放在在与正确的“跟踪”编号相对应的所有行中。

d = {"Trace": [1,1,1,1,1,2,2,2,2,2], "Sample": [1,2,3,4,5,1,2,3,4,5], "Value": [2,3,5,6,1,8,9,5,4,3]}

Any ideas? 有任何想法吗?

Thanks! 谢谢!

You can try this, filter your dataframe first, then groupy with mean, and join back to original dataframe on 'Trace' (which is the common column name between the dataframes are reset_index on results of groupby): 您可以尝试此操作,首先过滤数据框,然后使用均值进行分组,然后在“跟踪”上联接回原始数据框(这是数据reset_index之间的通用列名,是groupby结果的reset_index ):

df[df['Sample'].isin([3,4,5])].groupby('Trace')['Value'].mean()\
                              .rename('Avg Value').reset_index().merge(df)

Output: 输出:

   Trace  Avg Value  Sample  Value
0      1          4       1      2
1      1          4       2      3
2      1          4       3      5
3      1          4       4      6
4      1          4       5      1
5      2          4       1      8
6      2          4       2      9
7      2          4       3      5
8      2          4       4      4
9      2          4       5      3

OR 要么

df.groupby('Trace')\
  .apply(lambda x: x.loc[x['Sample'].isin([3,4,5]),'Value'].mean())\
  .rename('Avg Value').reset_index().merge(df)

Output: 输出:

   Trace  Avg Value  Sample  Value
0      1        4.0       1      2
1      1        4.0       2      3
2      1        4.0       3      5
3      1        4.0       4      6
4      1        4.0       5      1
5      2        4.0       1      8
6      2        4.0       2      9
7      2        4.0       3      5
8      2        4.0       4      4
9      2        4.0       5      3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM