Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据其他列上的条件完成字符串列_Python_Pandas_Dataframe_Apply - Fatal编程技术网

Python 根据其他列上的条件完成字符串列

Python 根据其他列上的条件完成字符串列,python,pandas,dataframe,apply,Python,Pandas,Dataframe,Apply,让我们以这个数据帧为例: 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”中的值具有完全相同的符号,我想

让我们以这个数据帧为例:

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”中的值具有完全相同的符号,我想在“Label”列的值中添加“_same_sign”。我想我必须使用应用程序,我尝试了以下方法,但无效(我对应用程序不太熟悉,如果这会伤害到您,请道歉):

你能帮我找到正确的密码吗

预期输出:

    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
使用和
轴=1的循环解决方案

df['Label'] = df.apply(lambda x : x['Label'] + '_same_sign' if x['V1']*x['V2']>0 else x['Label'], axis=1)
非循环解决方案,包括:

或与:


谢谢你@jezrael。你会建议一种方法而不是另一种吗?@Ewdlam-我的意见是最后一种。
df['Label'] = df.apply(lambda x : x['Label'] + '_same_sign' if x['V1']*x['V2']>0 else x['Label'], axis=1)
m = df['V1']*df['V2']>0

df['Label'] = df['Label'].mask(m ,df['Label'] + '_same_sign')
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'