首页 > 解决方案 > 如何在 Pandas 中使用 for 循环为每一列分配运行值?

问题描述

我有两个数据框,都具有相同的形状。

自由度

    2008LG  2007LG  2006LG  2005LG
0   44      65      30      20
1   10      16      56      70
2   65      30      20      122
3   0.0     0.00    679     158
4   0.0     0.00    30      20

东风

     2008Net    2007Net      2006Net    2005Net
0           0         0            0    452
1           0         0            0    365
2           0         0            0    778
3           0         0            0    78
4           0         0            0    60

计算逻辑是:对于 dfB 中的每一行,从最后2005Net一列开始并使用2005LG-2005net并获得一个分配给2005Net.

例如:对于第一次迭代2005LG- 2005Net= 20-452 =-432并分配-4322006Net. 第二次迭代将从2006LG- 2006Net= 30 - -432= 462 开始并分配给2007Net.

下面是我的代码,但它没有剪切它,这里到底有什么问题?

import pandas as pd
import numpy as np
from tqdm import tqdm

for index in tqdm(range(dfA.shape[0])):
    for col_index in reversed(range(4)):
        the_value = 0
        the_value = dfA[dfA.columns[col_index]].iloc[index] - dfB[dfB.columns[col_index]].iloc[index]       
        dfB[dfB.columns[col_index-1]].iloc[index] = the_value


标签: pythonpandasdataframe

解决方案


尝试这样的事情。

for index in reverse(range(4)):
    dfB[index - 1] = dfA.iloc[:, index] - dfB.iloc[:,index] 

这假设您要减去的每一列都具有相同的长度。


推荐阅读