python - 如何在 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
并分配-432
给2006Net
. 第二次迭代将从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
解决方案
尝试这样的事情。
for index in reverse(range(4)):
dfB[index - 1] = dfA.iloc[:, index] - dfB.iloc[:,index]
这假设您要减去的每一列都具有相同的长度。
推荐阅读
- xaml - Xamarin - 将 textchange 和 unfocus 事件分配给文本框(密码)
- class - Fortran - 如何为具有相同父级的不同类的数组编写用户定义的 I/O?
- mysql - 值对的 MySQL 唯一键/约束,无论它们在哪一列
- android - 屏幕关闭时,quickblox 示例视频聊天未接听电话
- c# - 导航到已在 Backstack 中查看
- google-sheets - 如何使用 ARRAYFORMULA 处理数组数组
- javascript - 组件自动完成 VueJS
- javascript - 单击链接时关闭全屏导航覆盖
- java - Junit 测试运行冻结
- scala - 检查文件路径扩展是否存在逻辑。斯卡拉