【问题标题】:Assign column with conditional values based on strings contained in other columns根据其他列中包含的字符串为列分配条件值
【发布时间】:2018-12-19 03:22:08
【问题描述】:

我正在尝试根据可能包含在其他列中的字符串来分配列。例如

var1 = 67

columns = {'col1': ['string1', 'thang2', 'code3', 'string2'], 
          'col2': [1, 2, np.nan, 3], 'col3': ['I', 'cant', 'think', 'what']}

df = pd.DataFrame(data = columns)

然后我如何创建第四列col4,即大多数时间为col3 + var1 + col1,但只要col2nan(在同一行中)并附加-W,则为np.nan每当col1 中的任何字符串中存在'in' 时(再次,在同一行中),它​​的值?

我对@9​​87654330@ 了如指掌,但我不知道如何在分配中执行所有这些条件操作,或者在创建列后是否有办法执行此操作,我也不确定。

【问题讨论】:

    标签: python pandas dataframe assign


    【解决方案1】:

    你可以用np.where试试这个:

    df['col4'] = np.where(df['col2'].notnull(),
                          df['col3'] + str(var1) + np.where(df['col1'].str.contains('in'),
                                                            df['col1'] + '-w',
                                                            df['col1']), 
                          np.nan)
    

    输出:

          col1  col2   col3             col4
    0  string1   1.0      I     I67string1-w
    1   thang2   2.0   cant     cant67thang2
    2    code3   NaN  think              NaN
    3  string2   3.0   what  what67string2-w
    

    或者如果你想使用assign

    df.assign(col5 = np.where(df['col2'].notnull(),
             df['col3'] + str(var1) + np.where(df['col1'].str.contains('in'),
                                               df['col1'] + '-w',
                                               df['col1']), 
             np.nan))
    

    输出:

          col1  col2   col3             col4             col5
    0  string1   1.0      I     I67string1-w     I67string1-w
    1   thang2   2.0   cant     cant67thang2     cant67thang2
    2    code3   NaN  think              NaN              NaN
    3  string2   3.0   what  what67string2-w  what67string2-w
    

    更新:既然你提到了速度。我想我会删除 .str 访问器并使用列表理解。

    df['col4'] = np.where(df['col2'].notnull(),
             df['col3'] + str(var1) + np.where(['in' in i for i in df['col1']], 
                                               df['col1'] + '-w', 
                                               df['col1']), 
             np.nan)
    

    【讨论】:

    • 哪个更快?这个特殊的 df 有大约 3000 万行,所以速度是一个因素。
    • 第一个应该更快。
    • 嵌套where 总是被低估。我的测试表明它实际上比 np.select 快 3 级嵌套。 +1
    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 2018-08-01
    • 1970-01-01
    • 2019-12-16
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多