从单行数据帧中减去数据帧的对应列

时间:2020-06-22 19:30:59

标签: python pandas dataframe

我有一个包含几行和几行的数据框

df1=
col_1 | col_2 | col_3 
---------------------
  1   |   3  |   5
  3   |   4  |   8
  2   |   4  |   2

和另一个具有单行的数据框

df2=
col_1 | col_2 
-------------
  1   |   2  

我想从第一行的所有行中减去第二个数据帧的对应列的值。我可以做到

for col in df2.columns.tolist():
   df1[col] = df1[col] - df2[col].to_numpy()[0]

结果将是

   col1 | col2 | col3
---------------------
     0  |   1   |  5
     2  |   2   |  8
     1  |   2   |  2

我想知道大熊猫中是否有更有效的方法?

2 个答案:

答案 0 :(得分:4)

你可以做

df1=df1.sub(df2.iloc[0],axis=1).fillna(df1)
Out[364]: 
   col_1  col_2  col_3
0    0.0    1.0    5.0
1    2.0    2.0    8.0
2    1.0    2.0    2.0

reindex_like

df1-df2.reindex_like(df1).fillna(0)
Out[367]: 
   col_1  col_2  col_3
0    0.0    1.0    5.0
1    3.0    4.0    8.0
2    2.0    4.0    2.0

或通过numpy

df1[:]=df1.values-df2.reindex(df1.columns, axis=1,fill_value=0).values
df1
Out[376]: 
   col_1  col_2  col_3
0      0      1      5
1      2      2      8
2      1      2      2

答案 1 :(得分:0)

一种很酷的方法:

(df1[['col_1', 'col_2']] - pd.concat([df2] * df1.shape[0], ignore_index=True)).join(df1['col_3'])

   col1  col2  col3
0     0     1     5
1     2     2     8
2     1     2     2