python-3.x - 使用df索引范围的条件

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

我想使用给定两个数据帧的df1中所述的ip range将区域列添加到df2中:


df1具有ip_address
df2具有ip_fromip_toregion


可以使用索引进行条件语句吗?
如果df1.ip[0]在特定ip之间,则在df1中添加区域?
我猜想if语句中应该有一个循环,以便它可以循环遍历df2来查看ip范围在哪里,并抓住该区域。

enter image description here

我知道手动添加每个条件都可以,
但是有没有办法使条件按索引循环?

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'])

最佳答案

您可以使用索引与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]])

关于python-3.x - 使用df索引范围的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56238743/

相关文章:

python - 如何在 Django 中进行分层验证?

python - TensorFlow 2.1 调用 cuInit : UNKNOWN ERROR (303) 失败

python - 具有多个基类的多重继承

python - 如何将元组内的字典列表转换为表格数据/pandas DataFrame?

C if 语句将两个整数变量与同一个常量进行比较

c# - Hololens TCP 套接字 - Hololens 服务器的 Python 客户端

Python - 减少重复项列表,但如果它们交替出现,则保留列表中的重复项

python - 在 pandas 中使用 lstrip 时删除多余的字符

arrays - 有人可以帮我微调这段代码中的 **else if** 语句吗?

JavaScript if 语句忽略某些变量的值,但不忽略其他变量的值