2017-05-03 235 views
3

如何動態地減去在大熊貓數據幀列中的值從指定的列:減去大熊貓列

date   deposit  A     B   C                   
0 2017-01-15 12   5     10   12 
1 2017-01-16 20   10    4   32 
2 2017-01-17 5    50    10   18 
3 2017-01-18 22   15    20   12 

減法列不日期或沉積(即A,B,C),從存款逐行:

date   deposit  A     B   C                   
0 2017-01-15 12   7     2   0 
1 2017-01-16 20   10    16   -12 
2 2017-01-17 5   -45    -5   -13 
3 2017-01-18 22   7     2   10 

回答

4
In [226]: df[['A','B','C']] = df.deposit.values[:, None] - df[['A','B','C']] 

In [227]: df 
Out[227]: 
     date deposit A B C 
0 2017-01-15  12 7 2 0 
1 2017-01-16  20 10 16 -12 
2 2017-01-17  5 -45 -5 -13 
3 2017-01-18  22 7 2 10 
0
for c in ['A','B','C']: 
    df[c]=df['deposit']-df[c] 
2

loc + rsub

cols = ['A', 'B', 'C'] 
df.loc[:, cols] = df[cols].rsub(df.deposit, 0) 
df 


     date deposit A B C 
0 2017-01-15  12 7 2 0 
1 2017-01-16  20 10 16 -12 
2 2017-01-17  5 -45 -5 -13 
3 2017-01-18  22 7 2 10 

inplace
我這樣做是inplace

df.update(df[['A', 'B', 'C']].rsub(df.deposit, 0)) 

df 

     date deposit A B C 
0 2017-01-15  12 7 2 0 
1 2017-01-16  20 10 16 -12 
2 2017-01-17  5 -45 -5 -13 
3 2017-01-18  22 7 2 10 

copy
偏好 我的偏好整體

df.assign(**df[['A', 'B', 'C']].rsub(df.deposit, 0).to_dict('list')) 

     date deposit A B C 
0 2017-01-15  12 7 2 0 
1 2017-01-16  20 10 16 -12 
2 2017-01-17  5 -45 -5 -13 
3 2017-01-18  22 7 2 10