gpt4 book ai didi

python - 我想通过在我的数据框中添加 2 个连续的列来插入新列

转载 作者:行者123 更新时间:2023-12-01 11:12:11 25 4
gpt4 key购买 nike

我有一个包含大量列和重复模式的数据框。我喜欢在每个模式之间插入一列(差异),以便该列包含前几列的差异。也许我可以更好地描述它作为一个例子:

Existing DF Example:

A_x_y_z_1 A_x_y_z_2 B_a_b_c_1 B_a_b_c_2 C_3_y_w_1 C_3_y_w_2
2 1 7 1 2 3
5 5 9 5 1 4
1 3 1 3 2 2
3 8 0 2 3 1

Expected DF:

A_x_y_z_1 A_x_y_z_2 diff B_a_b_c_1 B_a_b_c_2 diff C_3_y_w_1 C_3_y_w_2 diff
2 1 -1 7 1 -6 2 3 1
5 5 0 9 5 -4 4 5 1
1 3 2 1 3 2 2 7 5
3 8 5 0 2 2 1 4 3

最佳答案

pd.concat

pd.concat([                                                       # concat all groups
d.assign(**{f'{k}_Diff': d[f'{k}_2'] - d[f'{k}_1']}) # New Col with 'Diff'
for k,d in df.groupby(lambda x: x.split('_', 1)[0], axis=1) # Group w/Callable
], axis=1)

A_1 A_2 A_Diff B_1 B_2 B_Diff C_1 C_2 C_Diff
0 2 1 -1 7 1 -6 2 3 1
1 5 5 0 9 5 -4 1 4 3
2 1 3 2 1 3 2 2 2 0
3 3 8 5 0 2 2 3 1 -2

关于python - 我想通过在我的数据框中添加 2 个连续的列来插入新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58768712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com