【问题标题】:How to replace NaNs with valid value from within Pandas group如何用 Pandas 组中的有效值替换 NaN
【发布时间】:2017-04-05 17:53:19
【问题描述】:

我想用同一组中的非 NaN 值替换 Pandas DataFrame 列中的 NaN。在我的情况下,这些是地理坐标,由于某种原因,某些数据点查找失败。例如:

df.groupby('place')

看起来像

place| lat | lng
-----------------
foo  | NaN | NaN
foo  | 1   | 4
foo  | 1   | 4
foo  | NaN | NaN
bar  | 5   | 7
bar  | 5   | 7
bar  | NaN | NaN
bar  | NaN | NaN
bar  | 5   | 7

==> 我想要的:

foo  | 1   | 4
foo  | 1   | 4
foo  | 1   | 4
foo  | 1   | 4
bar  | 5   | 7
bar  | 5   | 7
bar  | 5   | 7
bar  | 5   | 7
bar  | 5   | 7

在我的情况下,同一“地点”分组中的 lat/lng 值是恒定的,因此选择任何非 NaN 值都可以。我也很好奇我怎么能用例如填充。平均数/多数数。

【问题讨论】:

标签: python pandas


【解决方案1】:

将 groupby 与 ffill 和 bfill 一起使用

df[['lat', 'lng']]=df.groupby('place').ffill().bfill()

df:

    place   lat lng
0   foo 1   4
1   foo 1   4
2   foo 1   4
3   foo 1   4
4   bar 5   7
5   bar 5   7
6   bar 5   7
7   bar 5   7
8   bar 5   7    

【讨论】:

  • 谢谢,df[['lat', 'lng']]=df[['place','lat', 'lng']].groupby('place').ffill().bfill() 帮了我的忙。
【解决方案2】:

如果您在给定组中具有相同的值,则以下方法应该有效:

df = df.fillna(method = 'ffill').fillna(method = 'bfill')

【讨论】:

    【解决方案3】:

    用每组中的第一个有效值填充nan

    df.fillna(df.groupby('place').transform('first'))
    
      place  lat  lng
    0   foo  1.0  4.0
    1   foo  1.0  4.0
    2   foo  1.0  4.0
    3   foo  1.0  4.0
    4   bar  5.0  7.0
    5   bar  5.0  7.0
    6   bar  5.0  7.0
    7   bar  5.0  7.0
    8   bar  5.0  7.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-08
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2021-04-13
      • 2016-03-18
      • 2020-01-16
      相关资源
      最近更新 更多