【问题标题】:Merge rows based on range of variable根据变量范围合并行
【发布时间】:2017-01-26 16:58:48
【问题描述】:
df1:
 lower_bound_ip_address           upper_bound_ip_address    country
0              16777216.0                16777471          Australia
1              16777472.0                16777727          China
2              16777728.0                16778239          China
3              16778240.0                16779263          Australia
4              16779264.0                16781311          China

df: 
     ip_address
0    7.327584e+08
1    3.503114e+08
2    2.621474e+09
3    3.840542e+09
4    4.155831e+08
5    2.809315e+09
6    3.987484e+09
7    1.692459e+09
8    3.719094e+09
9    3.416747e+08

我是 python 新手。 我想将 df['ip_address'] 与 df1['country'] 匹配。一定的ip_address范围对应特定的国家,例如:729808896-734003199表示日本。该怎么做?

我写了以下代码,但是有错误。 TypeError: len() of unsized object

for x in df['ip_address']:
    if x<=df1['upper_bound_ip_address'] and x>=df1['lower_bound_ip_address']:
        df['country']=df1['country']

【问题讨论】:

  • 将您的数据框发布为文本而不是 iages,错误是什么
  • TypeError: len() of unsized object
  • 将您的数据框发布为文本而不是图像

标签: python pandas merge


【解决方案1】:

pandas
pd.merge_asof + query

pd.merge_asof(
    df.sort_values('ip_address'), df1,
    left_on='ip_address', right_on='lower_bound_ip_address'
).query('ip_address <= upper_bound_ip_address')[['ip_address', 'country']]

numpy
np.searchsorted

b = df1.values[:, :2].ravel()
c = df1.country.values
ip = df.ip_address.values
srch = b.searchsorted(ip) // 2
mask = (ip >= b[0]) & (ip <= b[-1])
df.loc[mask, 'country'] = c[srch[mask]]

【讨论】:

    【解决方案2】:

    我认为您正在寻找的东西会更像这样......

    for x in df['ip_address']:
        for y in df1:
            if x<=y['upper_bound_ip_address'] and x>=y['lower_bound_ip_address']:
                x['country']=y['country']
    

    这是假设 df 是一个字典列表。如果数字落在正确的范围内,这会将国家/地区附加到每个字典中。

    【讨论】:

    • 我运行了代码,它给了我一个错误。 TypeError:字符串索引必须是整数
    • 将“for x in df['ip_address']”替换为“for x in df”
    【解决方案3】:
    for x in range(0, len(df)):
        for y in range(0, len(df1)):
            if (df.iloc[x,'ip_address'] <= df1.iloc[y,'upper_bound_ip_address'] and (df.iloc[x,'ip_address'] >= df1.iloc[y,'lower_bound_ip_address']):
                df['country']=df1.iloc[y,'country']
    

    @Geoff 的回答和这个有什么区别?

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多