【问题标题】:Pandas merge two dataframes based on one column from one table lies in between two columns from another table [duplicate]Pandas基于一个表中的一列合并两个数据框,位于另一个表的两列之间[重复]
【发布时间】:2020-04-18 02:32:23
【问题描述】:

我在其中一列中有一个带有 ip 地址的数据框,我想添加一个新列 根据位于较低和较高 IP 地址之间的 IP 地址的位置,从另一个数据帧中称为“国家/地区”。

两个数据框

import numpy as np
import pandas as pd

df1 = pd.DataFrame({'ip': [0.1,2.5,3.5]})

df2 = pd.DataFrame({'low_ip': [3,2,7,10],
                   'high_ip': [5,3,9,11],
                   'country': ['A','B','A','C']})

print(df1)
    ip
0  0.1
1  2.5
2  3.5

print(df2)
   low_ip  high_ip country
0       3        5       A
1       2        3       B
2       7        9       A
3      10       11       C

必填

ip    country
0.1   NA
2.5   B   because: 2 <= 2.5 <= 3
3.5   A   because: 3 <= 3.5 <= 5

【问题讨论】:

  • 你为什么使用 pd Dataframe 而不是字典?
  • 这只是一个例子,实际上数据框还包含许多其他列。
  • 我没有测试过性能或任何东西,但this answer 对一个几乎相同的问题给出了另一种可能更适合大型数据集的方法,尽管它确实重新索引df1跨度>
  • @RishiG 感谢非常有用的链接。赞成给定的链接。

标签: python pandas


【解决方案1】:

快速而肮脏的方式:

countries = []
for i in range(len(df1)):
    ip = df1.loc[i, 'ip']
    country = df2.query("low_ip <= @ip <= high_ip")['country'].to_numpy()

    if len(country) > 0:
        countries.append(country[0])
    else:
        countries.append('NA')

df1['country'] = countries

print(df1)

    ip country
0  0.1      NA
1  2.5       B
2  3.5       A

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 2019-08-03
    • 2019-12-16
    • 2021-12-16
    • 1970-01-01
    • 2021-01-11
    • 2022-01-25
    • 2015-09-20
    • 1970-01-01
    相关资源
    最近更新 更多