【发布时间】: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