【问题标题】:Create a column in dataframe using lambda based on another columns with non-null values基于具有非空值的另一列,使用 lambda 在数据框中创建一列
【发布时间】:2019-01-08 13:05:16
【问题描述】:

我有带有电影标题的数据框和带有流派的列。例如标题为“One”的电影是“Action”和“Vestern”,因为在相应的列中有“1”。

   Movie  Action  Fantasy  Vestern
0    One       1        0        1
1    Two       0        0        1
2  Three       1        1        0

我的目标是创建列genres,其中将包含特定电影所具有的每个流派的名称。 为此,我尝试使用 lambdalist comprehension,因为认为这会有所帮助。但是在运行如下代码行之后:

df['genres'] = df.apply(lambda x: [x+"|"+x for x in df.columns if x!=0])

我在每一行中只有NaN 值:

   Movie  Action  Fantasy  Vestern genres
0    One       1        0        1    NaN
1    Two       0        0        1    NaN
2  Three       1        1        0    NaN

也尝试使用groupby,但没有成功。

预期输出是:

   Movie  Action  Fantasy  Vestern          genres
0    One       1        0        1  Action|Vestern
1    Two       0        0        1         Vestern
2  Three       1        1        0  Action|Fantasy

要重现的代码:

import pandas as pd
import numpy as np

df = pd.DataFrame({"Movie":['One','Two','Three'],
                   "Action":[1,0,1],
                   "Fantasy":[0,0,1],
                   "Vestern":[1,1,0]})
print(df)

感谢您的帮助

【问题讨论】:

    标签: python pandas dataframe lambda list-comprehension


    【解决方案1】:

    为了提高性能可以使用dot all columns without first with all columns without last with separator, last remove last | by rstrip:

    df['new'] = df.iloc[:, 1:].dot(df.columns[1:] + '|').str.rstrip('|')
    print (df)
       Movie  Action  Fantasy  Vestern             new
    0    One       1        0        1  Action|Vestern
    1    Two       0        0        1         Vestern
    2  Three       1        1        0  Action|Fantasy
    

    或者使用列表推导来连接所有没有空字符串的值:

    arr = df.iloc[:, 1:].values * df.columns[1:].values
    df['new'] = ['|'.join(y for y in x if y) for x in arr]
    print (df)
       Movie  Action  Fantasy  Vestern             new
    0    One       1        0        1  Action|Vestern
    1    Two       0        0        1         Vestern
    2  Three       1        1        0  Action|Fantasy
    

    性能

    In [54]: %timeit (jez1(df.copy()))
    25.2 ms ± 2.31 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    In [55]: %timeit (jez2(df.copy()))
    61.4 ms ± 769 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    In [56]: %timeit (csm(df.copy()))
    1.46 s ± 35.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    
    
    
    df = pd.DataFrame({"Movie":['One','Two','Three'],
                       "Action":[1,0,1],
                       "Fantasy":[0,0,1],
                       "Vestern":[1,1,0]})
    #print(df)
    
    #30k rows
    df = pd.concat([df] * 10000, ignore_index=True)
    
    def csm(df):
        cols = df.columns.tolist()[1:]
        df['genres'] = df.apply(lambda x: "|".join(str(z) for z in [i for i in cols if x[i] !=0]) ,axis=1)
        return df
    
    def jez1(df):
        df['new'] = df.iloc[:, 1:].dot(df.columns[1:] + '|').str.rstrip('|')
        return df
    
    def jez2(df):
        arr = df.iloc[:, 1:].values * df.columns[1:].values
        df['new'] = ['|'.join(y for y in x if y) for x in arr]
        return df
    

    【讨论】:

    • @jezreal: 哈哈,你总是在时间和质量上打败我 :)
    【解决方案2】:
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({"Movie":['One','Two','Three'],
                       "Action":[1,0,1],
                       "Fantasy":[0,0,1],
                       "Vestern":[1,1,0]})
    
    cols = df.columns.tolist()[1:]
    
    df['genres'] = df.apply(lambda x: "|".join(str(z) for z in [i for i in cols if x[i] !=0]) ,axis=1)
    print(df)
    

    输出

    Movie  Action  Fantasy  Vestern          genres
    0    One       1        0        1  Action|Vestern
    1    Two       0        0        1         Vestern
    2  Three       1        1        0  Action|Fantasy
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-11
      • 2015-03-10
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2020-10-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多