【问题标题】:Condition using df index range使用 df 索引范围的条件
【发布时间】:2019-10-07 20:59:57
【问题描述】:

在给定两个数据框的情况下,我想使用df2 中所述的ip range 将区域列添加到df1

  • df1ip_address
  • df2ip_from, ip_to, region

你能用索引做一个条件语句吗? 如果df1.ip[0] 介于特定ip 之间,则在df1 中添加区域? 我猜 if 语句中应该有一个循环,以便它可以循环通过 df2 以查看 ip 范围在哪里并获取该区域。

我知道通过手动添加每个条件,这将起作用, 但是有没有办法通过索引进行条件循环?

region=[]
for row in df1['ip']:
    if row > 15:
        region.append('D')

    elif row > 10:
        region.append('C')

    elif row > 5:
        region.append('B')

    else:
        region.append('A')

df1['region'] = region

要让它遍历行,可以这样吗?

region = []
# For each row in the column,
for row in df1['ip']:
    if (row >= df2.loc[row,'ip_from']) and (row <= df2.loc[row,'ip_to']):
        region.append(df2.loc[row,'region'])

【问题讨论】:

  • 到目前为止你有什么尝试?您可以使用输入样本和预期输出来编辑您的帖子吗?
  • 我认为我可以使用带有索引的 if 循环来做到这一点:条件:如果 ip[i] 位于 ip_from 和 ip_to 之间,则区域。但它必须遍历整个数据帧以检查 ip[i] 位于哪个范围...
  • 请用您已经编写的代码编辑问题,我们会努力改进它。看看How to create a Minimal, Reproducible Example 什么是一个好的问题question ? 我们不会为你编写代码。

标签: python-3.x dataframe if-statement conditional-statements


【解决方案1】:

您可以使用索引与 IP 地址值匹配的区域列表:

df1 = {'ip': [13,4,7,2], 'region': []}
df2 = list('AAAAAABBBBBCCCCCDDDDD')
for i in range(len(df1['ip'])):
    df1['region'].append(df2[df1['ip'][i]])

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2012-05-14
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 2020-07-02
    • 2015-10-19
    相关资源
    最近更新 更多