我有兩個資料框,如下所示:-
data ={'a':[1,2,3,4,5,6,7],'b':[2,5,3,6,1,7,4]}
df = pd.DataFrame(data)
df
a b
0 1 2
1 2 5
2 3 3
3 4 6
4 5 1
5 6 7
6 7 4
data ={'a':[4,2,1,7,3,6,5],'c':[12,15,13,60,100,700,400]}
df1 = pd.DataFrame(data)
df1
a c
0 4 12
1 2 15
2 1 13
3 7 60
4 3 100
5 6 700
6 5 400
現在我想要一個使用上述兩個資料框的值串列。基本上,我想搜索其中的df行值df1并獲取相應的值(的列c)df1,然后通過取兩個數字的平均值將它們附加到一個串列中。
但是,我能夠做到,但是當我遍歷行時??,它需要時間。有沒有更好的方法可以更快地獲得解決方案?
代碼:
final=[]
for index, row in edges.iterrows():
for inde2x, row2 in df1.iterrows():
if np.isin(row['a'],row2['a']) == True:
r1 = row2['c']
if np.isin(row['b'],row2['a']) == True:
r2 = row2['c']
final.apped(r1 r2)
print(final)
例外輸出:
[28, 415, 200, 712, 413, 760, 72]
uj5u.com熱心網友回復:
一種方法是堆疊 的值,使用來自 的列進行df映射:adf1
out = df.stack().map(df1.set_index('a')['c']).groupby(level=0).sum()
輸出:
0 28
1 415
2 200
3 712
4 413
5 760
6 72
dtype: int64
如果你需要一個串列,你可以做out.tolist()
uj5u.com熱心網友回復:
利用map
mapper = df1.set_index('a').c.to_dict()
print(df['a'].map(mapper) df['b'].map(mapper))
0 28
1 415
2 200
3 712
4 413
5 760
6 72
dtype: int64
uj5u.com熱心網友回復:
d = df1.set_index("a")
df.applymap(lambda x: d.loc[x, "c"]).sum(1)
# 0 28
# 1 415
# 2 200
# 3 712
# 4 413
# 5 760
# 6 72
# dtype: int64
uj5u.com熱心網友回復:
使用基于查找的解決方案merge
res = sum(df.merge(df1, left_on=col, right_on='a', how='left')['c'] for col in 'ab').tolist()
輸出:
>>> res
[28, 415, 200, 712, 413, 760, 72]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/491331.html
