简体   繁体   English

Pandas - 从同一 dataframe 中的其他列中减去一列,用于具有不同列名和列数的多个文件

[英]Pandas - Subtract one column from other columns in same dataframe for multiple files with varying column names and number of columns

I want to subtract the 3rd from the right column from all other columns except for itself and the last column, then create new columns with these values with the header including the original column's header. The column names and the number of columns between each file vary, but the names of the 2 most right columns are always the same.我想从除自身和最后一列以外的所有其他列中减去右列的第三列,然后使用 header 创建具有这些值的新列,包括原始列的 header。每个文件之间的列名和列数各不相同, 但最右边的 2 列的名称始终相同。

Example df:示例 df:

ROI005 ROI005 ROI008 ROI008 53141 53141 AVG平均值 ERR
2 2个 5 5个 1 1个 4 4个 1 1个
4 4个 2 2个 2 2个 3 3个 3 3个
3 3个 3 3个 1 1个 5 5个 2 2个

Desired output:所需的 output:

ROI005 ROI005 ROI008 ROI008 53141 53141 AVG平均值 ERR ROI005 - Background ROI005 - 背景 ROI008 - Background ROI008 - 背景 Average - Background平均 - 背景
2 2个 5 5个 1 1个 4 4个 1 1个 1 1个 4 4个 3 3个
4 4个 2 2个 2 2个 3 3个 3 3个 2 2个 0 0 1 1个
3 3个 3 3个 1 1个 5 5个 2 2个 2 2个 2 2个 4 4个

I've been using this to get the difference for the 3rd to last column using the below code.我一直在使用它来使用下面的代码来获取倒数第三列的差异。 I know that I can use df.iloc[: , : -3] for all but the last 3 columns, but I'm not sure how to combine this with df.iloc[: , -2] for multiple columns.我知道我可以将df.iloc[: , : -3]用于除最后 3 列以外的所有列,但我不确定如何将它与df.iloc[: , -2]结合用于多列。

import pandas as pd
import glob

files = glob.glob(r'C:\Users\Me\1Test' + '/*.txt')
for f in files:
    df = pd.read_table(f)
    df['Average - Background']  = df.iloc[ : , -2] - df.iloc[ : , -3]
    df.to_excel(f.replace('txt', 'xlsx'), 'Sheet1')

Data:数据:

{'ROI005': [2, 4, 3],
 'ROI008': [5, 2, 3],
 '53141': [1, 2, 1],
 'AVG': [4, 3, 5],
 'ERR': [1, 3, 2]}

We could subtract that particular column from the other columns horizontally using sub on axis=0 ;我们可以使用sub on axis=0水平地从其他列中减去该特定列; then join it back to df :然后join它回到df

out = (df.join(df.drop(df.columns[[-3,-1]], axis=1)
               .sub(df[df.columns[-3]], axis=0)
               .add_suffix(' - Background')))

Output: Output:

   ROI005  ROI008  53141  AVG  ERR  ROI005 - Background  ROI008 - Background   AVG - Background  
0       2       5      1    4    1                    1                    4                  3  
1       4       2      2    3    3                    2                    0                  1
2       3       3      1    5    2                    2                    2                  4

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

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