【问题标题】:Replace values greater than limit using lambda in multiple observational feature in pandas dataframe在 pandas 数据框中的多个观察特征中使用 lambda 替换大于限制的值
【发布时间】:2020-07-20 14:35:05
【问题描述】:

类似于this question,我有一个功能“preWeight”,它对每个 MotherID 都有多个观察值,我想将它转换为数据帧到一个新的数据帧,其中

  • 如果 preWeight>=4000 对于特定的 MotherID,无论剩余的观察结果如何,我都会将 preWeight 的值分配为“是”
  • 否则,如果特定 MotherID 的 preWeight

所以我想转换这个数据框:

    ChildID   MotherID   preWeight
0     20      455        3500
1     20      455        4040
2     13      102        2500
3     13      102        NaN
4     702     946        5000
5     82      571        2000
6     82      571        3500
7     82      571        3800

进入这个:

    ChildID   MotherID   preWeight
0   20        455        Yes
1   13        102        No
2   702       946        Yes
3   82        571        No

我试过这个:

df.groupby('MotherID')['preWeight'].apply(
    lambda x: 'Yes' if x>4000 in x.values else 'No').reset_index()

我收到以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

提前致谢。

【问题讨论】:

  • 对于相同的ChildIDMotherID,如果preWeight 一次低于4000 一次高于4000,preWeight 应该有什么值?

标签: python pandas


【解决方案1】:

pandas.DataFrame.any试试这个:

df.groupby(['ChildID','MotherID']).agg(lambda x: 'Yes' if (x>4000).any() else 'No').reset_index()

输出:

   ChildID  MotherID preWeight
0       13       102        No
1       20       455       Yes
2       82       571        No
3      702       946       Yes

【讨论】:

  • 我认为你的答案缺少 preWeight,所以应该是:df.groupby(['ChildID','MotherID'])['preWeight'].agg(lambda x: 'Yes' if (x>4000).any() else 'No').reset_index()
  • 还有,为什么这里用的agg函数不适用,有什么区别?
  • 没关系,因为有三列,当我分组时,索引成为前两列,所以,指定在这种情况下要修改的列,不没关系,因为它只剩下一列。 @sums22
  • Here 是关于 agg 和 apply 的区别。但在这种情况下,没有具体的原因。另外,如果有帮助,请考虑accepting the answer,谢谢:)。 @sums22
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多