根据其他列的条件完成一个字符串列

Complete a string column according to a condition on other columns

让我们使用这个示例数据框:

df=pd.DataFrame({'V1':[1,2,np.nan,4,np.nan], 'V2':[-9,8,-7,0,np.nan], 'Label':['a','b','c','d','e']})
    V1   V2 Label
0  1.0 -9.0     a
1  2.0  8.0     b
2  NaN -7.0     c
3  4.0  0.0     d
4  NaN  NaN     e

如果 'V1' 和 'V2' 中的值具有完全相同的符号,我想将“_same_sign”添加到 'Label' 列的值中。我想我必须使用 apply,我尝试了以下但它没有用(我对 apply 不是很熟悉,对不起,如果这伤害了你):

df['Label'] = df.apply(lambda x : x['Label'] + '_same_sign' if x['V1']*x['V2']>0 else x['Label'])

你能帮我找到正确的代码吗?

预期输出:

    V1   V2        Label
0  1.0 -9.0            a
1  2.0  8.0  b_same_sign
2  NaN -7.0            c
3  4.0  0.0            d
4  NaN  NaN            e

你的循环解决方案 DataFrame.applyaxis=1:

df['Label'] = df.apply(lambda x : x['Label'] + '_same_sign' if x['V1']*x['V2']>0 else x['Label'], axis=1)

非循环解决方案 Series.mask:

m = df['V1']*df['V2']>0

df['Label'] = df['Label'].mask(m ,df['Label'] + '_same_sign')

DataFrame.loc:

m = df['V1']*df['V2']>0

df.loc[m, 'Label'] +=  '_same_sign'
#working same like
#df.loc[m, 'Label'] =  df.loc[m, 'Label'] + '_same_sign'