【问题标题】:how to filter the values based on some condition PANDAS如何根据某些条件PANDAS过滤值
【发布时间】:2022-02-04 15:10:07
【问题描述】:

我想根据每个国家的 F 是否多于 M 来过滤并返回一列。例如,如果一个国家的 F 多于 M,则该列将返回 True,否则返回 False。我怎样才能在熊猫中做到这一点?请帮忙!非常感谢。

我已经过滤掉了国家代码和性别以及有多少。我只需要根据计数过滤并返回一个TF值

 NOC  Sex
AFG  M        2
AHO  M        1
ALG  F        3
     M       14
ANZ  F        2
           ... 
WIF  M        5
YUG  F       60
     M      330
ZAM  M        2
ZIM  F       22

【问题讨论】:

  • 我相信您的输入可能会发生变化。如现在所示,您有一个未命名的索引,一个带有 M/F 的 NOC 列和一个带有数字的 Sex 列

标签: python pandas filter conditional-statements


【解决方案1】:

您期望的输出不清楚,但您可以这样做:

(df.pivot(columns='NOC', values='Sex')
   .fillna(0)
   .assign(more_F=lambda d: d['F'].gt(d['M']))
)

如果您的输入是带有 MultiIndex 的系列:

(ser.unstack(level='Sex')
    .fillna(0)
    .assign(more_F=lambda d: d['F'].gt(d['M']))
)

输出:

NOC     F      M  more_F
AFG   0.0    2.0   False
AHO   0.0    1.0   False
ALG   3.0   14.0   False
ANZ   2.0    0.0    True
WIF   0.0    5.0   False
YUG  60.0  330.0   False
ZAM   0.0    2.0   False
ZIM  22.0    0.0    True

【讨论】:

    【解决方案2】:
    import pandas as pd
    
    # This is a sample dataframe.
    # Make sure that you switch out the name of your dataframe in the code.
    # This dataframe is called "df"
    df=pd.DataFrame({"SEX":("M", "F", "M")})
    
    # Define two counters
    # One counts the occurence of "F"
    f_counter=0
    # One counts the occurence of "M"
    m_counter=0
    
    # Now iterate through each entry in the column "SEX"
    for index in df.index:
        # Check if the entry is equal to "F"
        if df["SEX"][index] == "F":
            # If this is true, we will raise our F-counter by 1
            f_counter += 1
        else:
            # If this is not true, we will raise our M-counter by 1
            m_counter += 1
    
    # Initialize our compare variable
    compare=False
    #Compare the F-counter with the M-counter
    if f_counter > m_counter:
        # If we have more F than M, define counter as True
        compare=True
    else:
        # If we have more M than F, define counter as False
        compare=False
    
    # Print our result
    print(compare)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多