Python 熊猫在许多列之间采取成对差异

Python 熊猫在许多列之间采取成对差异,python,pandas,Python,Pandas,我有一个熊猫数据框,它有很多实际列(列名以\u act结尾)和投影列(列名以\u proj结尾)。除了实际和预计之外,还有一个日期列。现在,我想为所有这些添加一个错误列(按该顺序,即在其投影列旁边)。示例数据帧: date a_act a_proj b_act b_proj .... z_act z_proj 2020 10 5 9 11 .... 3 -1 . . 我想要的是: date a_act a_proj a_error b_act b_p

我有一个熊猫数据框,它有很多实际列(列名以
\u act
结尾)和投影列(列名以
\u proj
结尾)。除了实际和预计之外,还有一个
日期
列。现在,我想为所有这些添加一个错误列(按该顺序,即在其投影列旁边)。示例数据帧:

date a_act a_proj b_act b_proj .... z_act z_proj
2020  10     5      9     11   ....   3     -1
.
.
我想要的是:

date a_act a_proj a_error b_act b_proj b_error .... z_act z_proj z_error
2020  10     5       5      9     11     -2    ....   3     -1     4
.
.
实现这一点的最佳方法是什么,因为我有很多实际和预计的专栏?

您可以:

df = df.set_index('date')

# create new columns
columns = df.columns[df.columns.str.endswith('act')].str.replace('act', 'error')

# compute differences
diffs = pd.DataFrame(data=df.values[:, ::2] - df.values[:, 1::2], index=df.index, columns=columns)

# concat
res = pd.concat((df, diffs), axis=1)

# reorder columns
res = res.reindex(sorted(res.columns), axis=1)
print(res)
输出

      a_act  a_error  a_proj  b_act  b_error  b_proj  z_act  z_error  z_proj
date                                                                        
2020     10        5       5      9       -2      11      3        4      -1