我试图找到一种更有效的方法,通过迭代行将信息从一个数据帧传输到另一个数据帧。我有两个数据帧,一个在列中包含名为“id”的唯一值,在另一列中包含名为“region”的值:
dfkey = DataFrame({'id':[1122,3344,3467,1289,7397,1209,5678,1792,1928,4262,9242],
'region': [1,2,3,4,5,6,7,8,9,10,11]})
id region
0 1122 1
1 3344 2
2 3467 3
3 1289 4
4 7397 5
5 1209 6
6 5678 7
7 1792 8
8 1928 9
9 4262 10
10 9242 11
…另一个数据帧包含这些相同的ID,但现在有时重复,而且没有任何顺序:
^{pr2}$我想使用dfkey数据帧作为键来输入df2数据帧中每个id的区域。我已经用iterrows()找到了一种方法,但它涉及嵌套循环:
df2['region']=0
for i, rowk in dfkey.iterrows():
for j, rowd in df2.iterrows():
if rowk['id'] == rowd['id']:
rowd['region'] = rowk['region']
id other region
0 1792 3 8
1 1122 2 1
2 3344 3 2
3 1122 4 1
4 3467 3 3
5 1289 5 4
6 7397 7 5
7 1209 3 6
8 5678 1 7
实际的dfkey有43K行和df2 600K行。代码已经运行了一个小时了,所以我想知道是否有一种更有效的方法来实现这一点。。。
我将使用map()方法:
900K行
^{pr2}$df2
DF的计时:pandas.merge
可能是另一种解决方案。在相关问题 更多 >
编程相关推荐