首先,假设我们有以下数据框:
import pandas as pd
data = pd.DataFrame({'id':['1','2','3','4','5','6','7','8'],
'A':['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'],
'C':['10','10','10','30','50','60','50','8'],
'D':['9','8','7','6','5','4','3','2']})
print(data)
A C D id
0 foo 10 9 1
1 bar 10 8 2
2 foo 10 7 3
3 bar 30 6 4
4 foo 50 5 5
5 bar 60 4 6
6 foo 50 3 7
7 foo 8 2 8
我希望你能做的是找到匹配的行并进行一些计算。
for any two ids(idx, idy) in data.iterrows():
if idx.A == idy.A and idx.C = idy.C:
result = idx.D * idy.D
然后生成一个包含三列['id']
, ['A']
和 ['result']
的新数据帧。
因此,期望结果的几行是:
id A result
0 1 foo 63
1 3 foo 63
2 5 foo 15
3 7 foo 15
我已经尝试过,但结果要么是错误的逻辑,要么是错误的代码/数据格式。有人可以帮我吗?