【问题标题】:How to create a column that evaluates the output in 3 other columns in a pandas data frame?如何创建一个列来评估 pandas 数据框中其他 3 列的输出?
【发布时间】:2022-11-13 13:34:07
【问题描述】:

我有以下数据框(df)。

GovKeepSecure BankKeepSecure OtherKeepSecure Secure
Yes Yes Yes Yes
No No Yes No
No Neutral Yes Neutral

我正在寻找一个 python 函数来评估前 3 列,并返回在“安全”/第 4 列中出现超过 2 次的值。

例如,如果前 3 列(在同一行)中有 2 个或更多“否”,则“安全”列中的值会导致“否”。如果不满足此类条件,则“安全”列默认为“中性”。

我想知道我们将如何创建这样一个函数。

这是我正在尝试开发的方法。

import pandas as pd

def secure(row):
    if row["GovKeepSecure", "BankKeepSecure", OtherKeepSecure] == ["Yes", "Yes", "Yes"]:
             return "Yes"
    if row["GovKeepSecure", "BankKeepSecure", OtherKeepSecure] == ["Yes", "Yes", "No"]:
             return "Yes"
-------------------------------------------------------------------------------------(etc.)
df["Secure"] = df.apply(lambda row: secure(row), axis=1)

如果有更好的方法,请告诉我。非常感谢!

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以为此使用np.select

    a = df[['GovKeepSecure', 'BankKeepSecure', 'OtherKeepSecure']]
    
    yes_counts = a.eq('Yes').sum(1)
    no_counts  = a.eq('No').sum(1)
    df['Secure'] = np.select([yes_counts > no_counts,
                              yes_counts < no_counts],
                             ['Yes', 'No'],
                             default='Neutral')
    

    您也可以使用mode

    a.agg(lambda s: s.mode() if len(s.mode()) == 1 else 'Neutral', axis=1)
    

    【讨论】:

      【解决方案2】:

      这是一种方法

      # apply value_counts and take idxmax along a row
      # sort values, as when value count are equal, it takes the first value in the series
      # sorting helps makes neutral comes as first result
      
      df['Secure']=df.apply(lambda x: x.sort_values().value_counts().idxmax() , axis=1)
      df
      
          GovKeepSecure   BankKeepSecure  OtherKeepSecure      Secure
      0             Yes              Yes              Yes         Yes
      1              No               No              Yes          No
      2              No          Neutral              Yes     Neutral
      

      【讨论】:

      • 为什么sortvalue_counts() 之前?应用value_count后的订单是否有保证?
      • 当 Yes, No, Neutral 都是一个时,就像最后一行一样。 NO 是第一个值,在 idxmax 中返回。在这种情况下,排序会将 Neutral 置于首位
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 2020-08-18
      • 1970-01-01
      相关资源
      最近更新 更多