• 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
    
  • 相关阅读:
    软考
    码云
    vue和bpmnjs
    工作流引擎
    net core restapi
    工厂模式
    sqlmanage
    类的扩展
    导出excel
    拼图
  • 原文地址:https://www.cnblogs.com/beihangxuwei/p/14718902.html
Copyright © 2020-2023  润新知