【问题标题】:Pandas find the mean of DataFrame based on a conditional across multiple columnsPandas 根据跨多列的条件找到 DataFrame 的平均值
【发布时间】:2021-11-28 07:43:32
【问题描述】:

我正在尝试查找 20 岁以下女性的平均体重,我有以下 DataFrame,我已经将年龄转换为 int 并将体重转换为 float。

 age   weight     height   male
 39.0   88.636360   180.0   True
 64.0   75.000000   155.0  False
 17.0  100.000000   183.0  False
 35.0   63.636364   170.0  True
 18.0   70.454544   173.0  False

我试过df.groupby(['male','age'])['weight'].mean()[False],但它只返回如下内容:

age    
18.0    64.225121
19.0    65.499535
20.0    67.855026
21.0    69.622658
22.0    69.376862

我如何过滤它,以便它汇总所有 20 岁以下女性的体重,然后取平均值?

【问题讨论】:

  • 请发布您预期的输出数据框

标签: python python-3.x pandas


【解决方案1】:

除非我误解,否则不需要 groupby。您可以根据您的条件过滤数据框,然后取权重列的平均值。

df.loc[(~df["male"]) & (df["age"] < 20), "weight"].mean()

【讨论】:

  • 啊,谢谢,谢谢!,不用担心你没有误解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多