我有两个数据数组,如下所示。
我只需要查看A和B值,并匹配f_code(Data2中为F)和b_ID(Data2中为B)。如果它们匹配,我用Data2中该行的A或B值替换Data1中的“值”。因此,我想以一个新的Data1结尾,其中的“值”列反映了Data2中的数字。
我一直试图通过掩盖不匹配的位置来找到两个匹配的位置,但是很难最终得到原始的Data1,而只是需要修改的部分。< / p>
Data1_masked = Data1[Data1['F_Code'].isin(Data2['F'])]
我也考虑过编写for循环,但是我是Python的新手,所以我没有以正确的方式编写它
for a in Data1['F_Code']:
for b in Data1['B_ID']:
if a.isin(Data2['F']) and b.isin(Data2('B') and FF10['poll'].loc[a] == 'A'
FF10['Value'] = Data2['A']
for a in Data1['F_Code']:
for b in Data1['B_ID']:
if a.isin(Data2['F']) and b.isin(Data2('B') and FF10['poll'].loc[a] == 'B'
FF10['Value'] = Data2['B']
数据1
Species Value F_Code B_ID
C 0.00219819 55933 A1
A 0.382345 55933 A1
B 0.023 55933 A1
C 0.001973105 55933 A2
A 0.313388 55933 A2
B 0.00643 55933 A2
C 0.0733 6002 1
A 2377.9 6002 1
B 2354.1 6002 1
C 0.0738 6002 2
A 2998.6 6002 2
B 531 6002 2
C 0.0739 6002 3
A 3340 6002 3
B 510 6002 3
C 0.0781 6002 4
A 2307.2 6002 4
B 326.5 6002 4
A 0.00203
B 7.47E-05
C 0.13872 55510 GT-1
A 1.95 55510 GT-1
B 0.11 55510 GT-1
C 0.05 55542 2
A 2.3 55542 2
B 0.1 55542 2
C 0.05 55542 1
A 2.28 55542 1
B 0.09 55542 1
数据2
F B A B
6002 1 2.54E+06 3.37E+05
6002 2 3.42E+06 4.70E+05
6002 3 5.35E+06 4.99E+05
6002 4 4.71E+06 4.84E+05
55510 GT-1 1.87E+03 1.03E+02
55542 1 6.72E+03 2.30E+02
55542 2 6.98E+03 2.47E+02
55933 A1 2.50E+04 1.42E+03
55933 A2 2.79E+04 1.56E+03
答案 0 :(得分:1)
稍微清理一下第二个DataFrame
,这样您就可以将它们合并在一起,并在三列匹配时替换Value列。这里重要的一步是.stack()
,它将使df2
中的一行代表不同的Species, Facility, Boiler
组合,这就是df1
的组织方式。
# Clean df2
df2 = (df2.rename(columns={'a': 'A'})
.set_index(['F', 'B'])
.stack()
.reset_index()
.rename(columns={'level_2': 'Species', 0: 'Value',
'F': 'f_code',
'B': 'B_ID'}))
# Bring information to df1
ids = ['f_code', 'B_ID', 'Species']
df1 = df1.merge(df2, on=ids, how='left', suffixes=['', '_repl'])
# Replace value where necessary, then drop the column we no longer need
df1.loc[df1.Value_repl.notnull(), 'Value'] = df1.loc[df1.Value_repl.notnull(), 'Value_repl']
df1 = df1.drop(columns='Value_repl')
输出:df1
Species Value f_code B_ID
0 C 0.002198 55933.000000 TPP1
1 A 25000.000000 55933.000000 TPP1
2 B 1420.000000 55933.000000 TPP1
3 C 0.001973 55933.000000 TPP2
4 A 27900.000000 55933.000000 TPP2
5 B 1560.000000 55933.000000 TPP2
6 C 0.073300 6002.000000 1
7 A 2540000.000000 6002.000000 1
8 B 337000.000000 6002.000000 1
9 C 0.073800 6002.000000 2
10 A 3420000.000000 6002.000000 2
11 B 470000.000000 6002.000000 2
12 C 0.073900 6002.000000 3
13 A 53C.000000 6002.000000 3
14 B 499000.000000 6002.000000 3
15 C 0.078100 6002.000000 4
16 A 4710000.000000 6002.000000 4
17 B 484000.000000 6002.000000 4
18 A 0.002030 nan NaN
19 B 0.000075 nan NaN
20 C 0.138720 55510.000000 GT-1
21 A 1870.000000 55510.000000 GT-1
22 B 103.000000 55510.000000 GT-1
23 C 0.0C 55542.000000 2
24 A 6980.000000 55542.000000 2
25 B 247.000000 55542.000000 2
26 C 0.0C 55542.000000 1
27 A 6720.000000 55542.000000 1
28 B 230.000000 55542.000000 1