且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

忽略NaN的Python pandas 的独特价值

更新时间:2023-02-16 16:44:03

尝试ffill

df.ffill().groupby('b').agg({'a': ['min', 'max', 'unique'], 'c': ['first', 'last', 'unique']})


      c                          a                 
  first last           unique  min  max      unique
b                                                  
0   foo  foo            [foo]  1.0  2.0  [1.0, 2.0]
1   bar  bar  [bar, foo, baz]  1.0  3.0  [1.0, 3.0]

如果Nan是该组的第一个元素,则上述解决方案将失效.从长远来看,@IanS的解决方案更好.

If Nan is the first element of the group then the above solution breaks. @IanS's solution is better in the long run.