我有这样的数据帧:熊猫使用外部变量应用功能
V1 V2
1 1
0 0
0 0
0 0
1 0
1 1
0 1
我需要比较称为comienzo一个变量中的每个V1和V2行值,并设置名为第三列标签下面这个函数:
def labeling(DataFrame):
comienzo=0 #flag to indicate event started (1= started, 0= no started)
for n in range(len(DataFrame)):
if ((DataFrame.iloc[n]['V1']==1 & DataFrame.iloc[n]['V2']==1) & comienzo == 0) :
comienzo=1
DataFrame['Label']='Start'
elif ((DataFrame.iloc[n]['V1']==0 & DataFrame.iloc[n]['V2']==0) & comienzo == 1) :
comienzo=0
DataFrame['Label']='End'
return DataFrame
我想要做的使用这pandorable。所以,我想这一点:
def labeling(x, comienzo):
if ((x['V1']==1 & x['V2']==1) & comienzo == 0) :
comienzo=1
Label='Start'
elif ((x['V1']==0 & x['V2']==0) & comienzo == 1) :
comienzo=0
Label='End'
return Label
comienzo=0 #I initialize 'comienzo' var to 0
DataFrame['Label']=DataFrame.apply(labmda x: labeling(x,comienzo),axis=1)
这项工作,但值不正确,我认为.apply
不考虑变量comienzo。
是否有可能使此代码变得可怜?
我想这样的输出:
comienzo=0
V1 V2
1 1 Start comienzo=1
0 1 NaN
0 0 End comienzo=0
0 0 NaN
1 0 NaN
1 1 Start comienzo=1
1 1 NaN
0 1 NaN
您是否试过 - '.apply(label,args =(comienzo,),axis = 1'? –
不,我不需要每行的_comienzo_值用于下一行 –