将数据从一个pandas数据帧传递到另一个数据帧的最有效方法

2024-09-28 05:44:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一种更有效的方法,通过迭代行将信息从一个数据帧传输到另一个数据帧。我有两个数据帧,一个在列中包含名为“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行。代码已经运行了一个小时了,所以我想知道是否有一种更有效的方法来实现这一点。。。


Tags: 数据方法in信息iddataframeforregion
2条回答

我将使用map()方法:

In [268]: df2['region'] = df2['id'].map(dfkey.set_index('id').region)

In [269]: df2
Out[269]:
     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

900K行df2DF的计时:

^{pr2}$

pandas.merge可能是另一种解决方案。在

newdf = pandas.merge(df2, dfkey, on='id')

In [22]: newdf
Out[22]: 
     id  other  region
0  1792      3       8
1  1122      2       1
2  1122      4       1
3  3344      3       2
4  3467      3       3
5  1289      5       4
6  7397      7       5
7  1209      3       6
8  5678      1       7

相关问题 更多 >

    热门问题