Pandas使用外部变量应用函数

时间:2017-09-01 15:30:05

标签: python pandas dataframe

我有这个Dataframe:

V1 V2    
1  1    
0  0    
0  0    
0  0    
1  0    
1  1    
0  1

我需要将每个 V1 V2 行值与一个名为 comienzo 的变量进行比较,并设置名为的第三列标签遵循此功能:

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

我想用Dataframe.apply来做这件事。所以,我试过这个:

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               

1 个答案:

答案 0 :(得分:1)

你有一系列的小错误,包括不正确的lambda使用(拼写错误的lambda),不使用args正确应用(如上所述),而且我漂亮确定你打算使用'和'代替&在条件逻辑中。

此外,您的输入数据为7行,而您的理想输出为8行,这使得尝试通过映射输入 - >输出来帮助解决问题,技术上不可能。

但是,我认为这是你想要的:

DataFrame = pd.DataFrame(
        [[1,1],
         [0,1],
         [0,0],
         [0,0],
         [1,0],
         [1,1],
         [0,1]])
DataFrame.columns=['V1','V2']
DataFrame.insert(0, 'comienzo', 0)

def labeling(x):  
    global comienzo
    if ((x['V1']==1 and x['V2']==1) and comienzo == 0 ) :
        comienzo=1
        return('s')
    elif ((x['V1']==0 and x['V2']==0) and comienzo == 1 ) :
        comienzo=0
        return('end')

comienzo=0
DataFrame['Label']=DataFrame.apply(labeling,axis=1)

请注意,通过使用全局for comienzo,我们可以通过应用迭代来保留其值。

虽然在很多情况下使用全局变量是不好的做法。进一步阅读:Why is it not possible to access other variables from inside the apply function in Python?

相关问题