Skip to main content
 首页 » 编程设计

python之如何将自定义百分比更改应用于 pandas 数据框

2024年09月07日8luoye11

我想将自定义百分比应用于我的数据框行,每个公司 ID 的最后一行应始终为零。我尝试使用 df.apply 方法但无法传递多个参数。感谢您能否让我知道有多少种方法可以解决这个问题?预先感谢您的关注和努力!!

df = pd.DataFrame({'CompanyId' : ['A','A','A','B','B'],                            
                 'stand_alone' : [10,12,-5,20,1]}) 
 
def get_change(current,previous): 
    if current==previous: 
        return 0 
    if current>=0 and previous<0: 
        chg=1.0 
    if current>=0 and previous==0: 
        chg=1.0 
    if current<0 and previous>0: 
        chg=-1.0 
    if current>0 and previous>0: 
        chg=abs(current)/abs(previous)-1 
    if current<0 and previous<0: 
        chg=abs(current)/abs(previous)-1 
        chg=-chg 
    return round(chg*100,2) 

输出应该如下:

CompanyId change    stand_alone 
    0   A   -16.67  10 
    1   A   100.00  12 
    2   A   0.00    -5 
    3   B   1900.00 20 
    4   B   0.00    1 

请您参考如下方法:

好的,这是使用您当前的逻辑执行此操作的一种方法。

def get_change(x): 
    x=x.sort_index(ascending=False) 
    cond1 = x == x.shift(1) 
    result1 = 0 
    cond2 = (x < 0) & x.shift(1) > 0 
    result2 = -1 
    cond3 = ((x>0) & (x.shift(1)>0)) | ((x<0) & (x.shift(1)<0)) 
    result3 = (x/x.shift(1)) - 1 
    cond4 = ((x>=0)&(x.shift(1)<=0))  
    result4 = 1 
    result = np.select([cond1,cond2,cond3,cond4],[result1,result2,result3,result4])*100 
    return result[::-1] 
 
df['change'] = df.groupby('CompanyId')['stand_alone'].transform(get_change).round(2) 
print(df) 

输出:

  CompanyId  stand_alone   change 
0         A           10   -16.67 
1         A           12   100.00 
2         A           -5     0.00 
3         B           20  1900.00 
4         B            1     0.00 

我认为您需要使用这种方法的关键函数是 np.select 一种执行 if-then-elseif 逻辑的方法,以及 groupby 和 transform 。