简体   繁体   English

遍历列并减去 pd.dataframe 中的最后一列

[英]Iterating through columns and subtracting with the Last Column in pd.dataframe

I am a python newbie and currently sitting on the evaluation of my simulations.我是一名 Python 新手,目前正在评估我的模拟。 I have read the results of the tab files into a pandas dataframe.我已将选项卡文件的结果读入熊猫数据框。
My index is the frequency.我的指标是频率。 The remaining columns represent the amplitude of the calculated PSD.其余列表示计算出的 PSD 的振幅。

I want to subtract these columns (eg a,b,c,d...) with the last column, which is my test data.我想用最后一列(我的测试数据)减去这些列(例如 a、b、c、d...)。

The first table is an example of my current Dataframe.第一个表是我当前 Dataframe 的示例。 I want to substract each column/row with the test_data to get at the end the Standard deviation etc. of each column like in the following table:我想用 test_data 减去每一列/行以得到每一列的标准差等,如下表所示:

frequency (index)频率(指数) A一种 B C C test_data测试数据
1 1个 1.2 1.2 5.0 5.0 2.4 2.4 1.9 1.9
2 2个 2.1 2.1 3.0 3.0 2.7 2.7 2.6 2.6
3 3个 3.0 3.0 6.0 6.0 2.9 2.9 2.8 2.8

The following table/dataframe is the wanted outcome after the loop.下表/数据框是循环后想要的结果。

frequency (index)频率(指数) A一种 B C C test_data测试数据
1 1个 test_data[1]-A[1]测试数据[1]-A[1] test_data[1]-B[1]测试数据[1]-B[1] test_data[1]-C[1]测试数据[1]-C[1] 1.9 1.9
... ... ... ... ... ... ... ... .... ....
3 3个 test_data[n]-A[n]测试数据[n]-A[n] test_data[n]-B[n]测试数据[n]-B[n] test_data[n]-C[n]测试数据[n]-C[n] 2.8 2.8
average of column列的平均值 0.33 0.33 -2.3 -2.3 -0.233 -0.233
frequency (index)频率(指数) A一种 B C C test_data测试数据
1 1个 0.7 0.7 -3.1 -3.1 -0.5 -0.5 1.9 1.9
2 2个 0.5 0.5 -0.4 -0.4 -0.1 -0.1 2.6 2.6
3 3个 -0.2 -0.2 -3.2 -3.2 -0.1 -0.1 2.8 2.8
average of column列的平均值 0.33 0.33 -2.3 -2.3 -0.233 -0.233

I woult be very very grateful for any help regarding the loop.我将非常感谢有关循环的任何帮助。

You can use drop to get rid of the non target columns, then rsub to subtract the test_data.您可以使用drop非目标列,然后rsub减去 test_data。 Finally concat to the original dataset:最后concat到原始数据集:

df2 = df.drop(columns=['frequency (index)', 'test_data']).rsub(df['test_data'] ,axis=0)

out = pd.concat([df.assign(**df2), df2.sum().to_frame().T])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM