【发布时间】:2018-09-24 08:48:56
【问题描述】:
我在 pandas 中有两个表:
df1:包含 150K 用户的用户 ID 和 IP_Addresses。
|---------------|---------------|
| User_ID | IP_Address |
|---------------|---------------|
| U1 | 732758368.8 |
| U2 | 350311387.9 |
| U3 | 2621473820 |
|---------------|---------------|
df2:包含IP地址范围和所属国家,139K条记录
|---------------|-----------------|------------------|
| Country | Lower_Bound_IP | Upper_Bound_IP |
|---------------|-----------------|------------------|
| Australia | 1023787008 | 1023791103 |
| USA | 3638734848 | 3638738943 |
| Australia | 3224798976 | 3224799231 |
| Poland | 1539721728 | 1539721983 |
|---------------|-----------------|------------------|
我的目标是在 df1 中创建一个国家/地区列,使 df1 的 IP_Address 位于 df2 中该国家/地区的 Lower_Bound_IP 和 Upper_Bound_IP 的范围之间。
|---------------|---------------|---------------|
| User_ID | IP_Address | Country |
|---------------|---------------|---------------|
| U1 | 732758368.8 | Indonesia |
| U2 | 350311387.9 | Australia |
| U3 | 2621473820 | Albania |
|---------------|---------------|---------------|
我的第一种方法是对两个表进行交叉连接(笛卡尔积),然后过滤到相关记录。但是,使用 pandas.merge() 进行交叉连接是不可行的,因为它将创建 210 亿条记录。代码每次都会崩溃。您能否提出一个可行的替代解决方案?
【问题讨论】:
-
IP_Address 范围是否全面?即,
df1中是否存在您希望Country为空的 IP_Address 值? -
@cmaher 我现在假设范围很全面,因此任何用户都不会有空国家/地区。
标签: python python-3.x pandas join merge