Pandas根据条件进行变换

huangapple go评论87阅读模式
英文:

Pandas transform with conditions

问题

以下是翻译好的部分:

这段代码首先进行分组,然后将所有小于3的值替换为NaN,然后使用最后一个值来填充。然而,对于ID为11的情况,在组B中的第一个观察值使用此方法获得了值9,这是组A的最后一个值。这不是期望的结果。这是因为当条件为True时,掩码返回NaN,而ffill()不考虑分组。

是否有一种巧妙的方法来解决这个问题,即将小于3的值替换为最后一个值,并且当组的第一个值小于3时,使用另一种方法,例如x.mean()来替换。

英文:

The code below make a groupby and then replaces all values below 3 with na and then use the last value instead.

However, for ID 11, the first observation in group B get the value 9 using this method, the last value of group A. This is not desirable. This happens because the mask returns NaN when True and the ffill() doesn't take the groupby into consideration.

Is there a smart way to solve this, to replace values below 3 with the last value, and, when the first value of a group is below 3, use another method, perhaps x.mean() to replace.

  1. import pandas as pd
  2. import numpy as np
  3. data = pd.DataFrame({'ID':list(range(1,21)),
  4. 'group':['A']*10 + ['B']*10,
  5. 'value':[4,6,2,9,7,5,1,9,8, 9, np.nan, 4,5,6,1,2,3,4,2,6]
  6. })
  7. data.groupby('group').transform(lambda x: x.mask(x < 3)).ffill()

答案1

得分: 1

使用ffill函数在lambda函数中,将第一个缺失值替换为mean

英文:

Use ffill in lambda function and replace first missing values by mean:

  1. data['value'] = (data.groupby('group')['value']
  2. .transform(lambda x: x.mask(x < 3).ffill().fillna(x.mean())))
  3. print (data)
  4. ID group value
  5. 0 1 A 4.000000
  6. 1 2 A 6.000000
  7. 2 3 A 6.000000
  8. 3 4 A 9.000000
  9. 4 5 A 7.000000
  10. 5 6 A 5.000000
  11. 6 7 A 5.000000
  12. 7 8 A 9.000000
  13. 8 9 A 8.000000
  14. 9 10 A 9.000000
  15. 10 11 B 3.666667
  16. 11 12 B 4.000000
  17. 12 13 B 5.000000
  18. 13 14 B 6.000000
  19. 14 15 B 6.000000
  20. 15 16 B 6.000000
  21. 16 17 B 3.000000
  22. 17 18 B 4.000000
  23. 18 19 B 4.000000
  24. 19 20 B 6.000000

  1. s = data.groupby('group')['value'].transform('mean')
  2. data['value']=data['value'].mask(data['value'] < 3).groupby(data['group']).ffill().fillna(s)
  3. print (data)
  4. ID group value
  5. 0 1 A 4.000000
  6. 1 2 A 6.000000
  7. 2 3 A 6.000000
  8. 3 4 A 9.000000
  9. 4 5 A 7.000000
  10. 5 6 A 5.000000
  11. 6 7 A 5.000000
  12. 7 8 A 9.000000
  13. 8 9 A 8.000000
  14. 9 10 A 9.000000
  15. 10 11 B 3.666667
  16. 11 12 B 4.000000
  17. 12 13 B 5.000000
  18. 13 14 B 6.000000
  19. 14 15 B 6.000000
  20. 15 16 B 6.000000
  21. 16 17 B 3.000000
  22. 17 18 B 4.000000
  23. 18 19 B 4.000000
  24. 19 20 B 6.000000

huangapple
  • 本文由 发表于 2023年5月15日 14:53:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76251529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定