简体   繁体   English

在熊猫中取条件均值

[英]take a conditional mean in pandas

I have a data set like this:我有一个这样的数据集:

在此处输入图片说明

I want to take the mean of LCR in each year for WFR=1 and WFR=0 separately, for example in 2018 I have 4 WFR=0 so take the mean of LCR for it and for WFR=1 I have just one.我想分别取 WFR=1 和 WFR=0 每年 LCR 的平均值,例如在 2018 年我有 4 个 WFR=0,所以取 LCR 的平均值,对于 WFR=1 我只有一个。 any idea?任何的想法? thanks谢谢

You can groupby by year and WFR.您可以按年份和 WFR 分组。 This will create every combination that exists in your dataset.这将创建数据集中存在的每个组合。 If all conditions are not in your dataframe you can create a base dataframe with all conditions and merge with it.如果所有条件都不在您的数据框中,您可以创建一个包含所有条件的基本数据框并与之合并。

df = data_new4.groupby(['CLOSDATE_year', 'WFR'])['LCR'].mean()

to plot the data you can use the seaborn library.要绘制数据,您可以使用 seaborn 库。

import seaborn as sns

sns.lineplot(data=df, hue='WFR', x='CLOSDATE_year', y='LCR')

Try with groupby :尝试使用groupby

>>> data.groupby(["CLOSDATE_year", "WFR"])["LCR"].mean()

CLOSDATE_year  WFR
2011           1      268.750000
2012           1      235.533333
2018           0      192.775000
               1      186.000000
Name: LCR, dtype: float64

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

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