【问题标题】:Column-wise subtraction calculations in python 3python 3中的按列减法计算
【发布时间】:2022-01-06 13:43:20
【问题描述】:

这似乎很简单,但我似乎无法在 Python 3 中找到解决此问题的有效方法:我可以在我的数据框中使用一个循环来获取当前列之后的每一列(从第一列开始) , 并从当前列中减去它,以便我可以将该结果列添加到新的数据框中?

这是我的数据的样子:

这是我目前所拥有的,但是在运行run_analysis 时,我的“结果”方程式出现错误,我不知道如何将结果存储在新的数据框中。我是所有这一切的初学者,所以任何帮助将不胜感激。

storage = [] #container that will store the results of the subtracted columns
def subtract (a,b): #function to call to do the column-wise subtractions
    return a-b

def run_analysis (frame, store):
    for first_col_index in range(len(frame)): #finding the first column to use
        temp=[] #temporary place to store the column-wise values from the analysis
        for sec_col_index in range(len(frame)): #finding the second column to subtract from the first column
            if (sec_col_index <= first_col_index): #if the column is below the current column or is equal to 
                                                   #the current column, then skip to next column
                continue
            else:
                result = [r for r in map(subtract, frame[sec_col_index], frame[first_col_index])]
            #if column above our current column, the subtract values in the column and keep the result in temp
                temp.append(result)
        store.append(temp) #save the complete analysis in the store

【问题讨论】:

  • 不要发布带有数据框的图像,而是将文本放在这里。这将使其他人的调试变得容易。
  • 请检查此stackoverflow.com/questions/20109391/… 并相应地编辑您的问题。
  • 感谢您的评论!我希望这更容易

标签: python pandas dataframe loops for-loop


【解决方案1】:

这样的?

#dummy ddataframe
df = pd.DataFrame({'a':list(range(10)), 'b':list(range(10,20)), 'c':list(range(10))})
print(df)

输出:

   a   b  c
0  0  10  0
1  1  11  1
2  2  12  2
3  3  13  3
4  4  14  4
5  5  15  5
6  6  16  6
7  7  17  7
8  8  18  8
9  9  19  9

现在迭代成对的列并减去它们,同时将另一列分配给数据框

for c1, c2 in zip(df.columns[:-1], df.columns[1:]):
    df[f'{c2}-{c1}'] = df[c2]-df[c1]
print(df)

输出:

   a   b  c  b-a  c-b
0  0  10  0   10  -10
1  1  11  1   10  -10
2  2  12  2   10  -10
3  3  13  3   10  -10
4  4  14  4   10  -10
5  5  15  5   10  -10
6  6  16  6   10  -10
7  7  17  7   10  -10
8  8  18  8   10  -10
9  9  19  9   10  -10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2020-12-06
    • 2012-04-10
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    相关资源
    最近更新 更多