pandas groupby 字段存在None值的坑

import pandas as pd

def test(tmp_df: pd.DataFrame):
    print(tmp_df)

df = pd.DataFrame([{'name': 'xw', 'org': 1232, 'num': 1}, {'name': 'xw', 'org': None, 'num': 1},
                   {'name': 'xw', 'org': 1232, 'num': 1}, {'name': 'xws', 'org': 1232, 'num': 1}])

df.groupby(['name', 'org']).apply(test)
  • 结果,你会发现含有None值的字段直接被groupby忽略了,所以在用groupby时要保证groupby涉及的所有字段的值都不为None,df = df.where(df.notnull(), '')
  name     org  num
0   xw  1232.0    1
2   xw  1232.0    1


  name     org  num
3  xws  1232.0    1

import pandas as pd

def test(tmp_df: pd.DataFrame):
    print(tmp_df)



df = pd.DataFrame([{'name': 'xw', 'org': 1232, 'num': 1}, {'name': 'xw', 'org': '', 'num': 1},
                   {'name': 'xw', 'org': 1232, 'num': 1}, {'name': 'xws', 'org': 1232, 'num': 1}])

df.groupby(['name', 'org']).apply(test)
  name   org  num
0   xw  1232    1
2   xw  1232    1

  name org  num
1   xw        1

  name   org  num
3  xws  1232    1
posted @ 2021-04-29 17:34  bhxuwei  阅读(790)  评论(0编辑  收藏  举报