代码之家  ›  专栏  ›  技术社区  ›  Vaebhav

检查Groupby是否为空

  •  1
  • Vaebhav  · 技术社区  · 5 年前

    row_key

    我知道这个标准 empty DataFrame ,但找不到类似的 DataFrameGroupBy

    import pandas as pd
    from io import StringIO
    
    df = pd.read_csv(StringIO("""
    Name,Value,row_key,row_label
    XYZ,100,abc,"Label - 2"
    ASD,100,abc,"Label - 2"
    GHJ,1000,abc,"Label - 2"
    KLI,100,abc,"Label - 2"
    BHY,1009,bnm,"Label - 2"
    TGB,1409,bnm,"Label - 2"
    YUJ,1509,bnm,"Label - 2"
    KUT,1609,bnm,"Label - 2"
    """))
    
    invalid_row_key = 'fgh'
    
    filter_df = df[df['row_key'] == invalid_row_key].groupby('row_label')
    
    #### I want something similar to below if case , to handle if the filter_df is empty
    if filter_df.empty:
       print("No Row Key Present")
    
    

    我知道我可以用 recent_index

    1 回复  |  直到 5 年前
        1
  •  1
  •   cs95 abhishek58g    5 年前

    查询 .ngroups

    if not filter_df.ngroups:
        # no row key present
    

    看到了吗 this post by me ngroups .


    上面的答案假设您无法在创建groupBy对象之前进行判断,但是如果可以的话,最好在条件步骤进行检查,然后可以检查 DataFrame.empty 属性更直观:

    filter_df = df[df['row_key'] == invalid_row_key]
    if filter_df.empty:
        # no rows present
    else:
        filter_df.groupby('row_label').doSomethingElse()
    
        2
  •  0
  •   Vaebhav    5 年前

    最好的处理方法是过滤 dataframe

    不过,我自己尝试了以下解决方案。

    
    if filter_df.size().empty:
       print("Empty DataFrame")