【问题标题】:Optimize Apply to create an list of string with Boolean columns优化应用以创建带有布尔列的字符串列表
【发布时间】:2021-10-25 22:08:47
【问题描述】:

我必须检查行中的布尔值,获取列的名称以构建列表并使用此字符串列表创建新列。

我有这段代码,它运行良好,但速度很慢(我使用了 125 000 行 20 列)。您有优化此代码的想法吗?

import pandas as pd 

def exlusions(x: pd.Series) -> pd.Series:
        reasons = [name for name in x.index if x[name] == True]
        return ",".join(reasons)

dct_data = {
    'A' : [False, False, True, False, True, False],
    'B' : [False, False, False,False, False, False],
    'C' : [False, True, False,False, False, False],
    'D' : [False, False, True, False, False, False],
    'Client' : ['Paul', 'Nick', 'Josh', 'Flo', 'Julia', 'Lucia']
}

df = pd.DataFrame(dct_data)
df = df[list(df.select_dtypes(include='bool').columns) + ['Client']]
df = df[df[list(df.select_dtypes(include='bool').columns)].any(1)]
df['Exclusions'] = df.apply(lambda x: exlusions(x), axis=1)

df

【问题讨论】:

    标签: python pandas lambda apply


    【解决方案1】:

    我们可以在列中使用DataFrame.dot,在额外的逗号中使用str.rstrip

    # Boolean Columns
    cols = df.columns[df.dtypes == 'bool']
    # Filter DataFrame rows
    df = df[df[cols].any(axis=1)]
    # Take dot product (multiply then sum rows) and remove trailing comma
    df['Exclusions'] = df[cols].dot(cols + ',').str.rstrip(',')
    

    df:

           A      B      C      D Client Exclusions
    1  False  False   True  False   Nick          C
    2   True  False  False   True   Josh        A,D
    4   True  False  False  False  Julia          A
    

    【讨论】:

      猜你喜欢
      • 2017-08-11
      • 2021-01-31
      • 2021-03-12
      • 2023-03-04
      • 2014-08-06
      • 2017-10-05
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      相关资源
      最近更新 更多