我有以下内容:

import pandas as pd
ls = [(1,2,10,20,5),
      (3,4,30,40,10),
      (5,6,50,60,20)]
df_ = pd.DataFrame({'col1': [1.1, 3.5, 5.4, 4.1],
              'col2': [11, 35, 44, 41]})

我想在df_中创建一个新列,该列将根据以下规则创建: 判断ls的每个数组:

  • 如果col 1位于多元组的第1个和第2个元素之间
  • 如果col 2位于多元组的第3个和第4个元素之间
  • 如果上述2个条件中有both个为真,那么它应该返回数组的第5个元素,否则它应该返回无

生成的框架应该是这样的:

df_ = pd.DataFrame({'col1': [1.1, 3.5, 5.4, 4.1],
                  'col2': [11, 35, 54, 41],
    'result': [5, 10, None, None]})

我怎么能做到呢?

推荐答案

一个有效的 Select 是使用janitorconditional_join:

# pip install pyjanitor
import janitor

out = df_.conditional_join(
         pd.DataFrame(ls)
           .rename(columns={4: 'result'})
           .astype({0: df_['col1'].dtype, 1: df_['col1'].dtype,
                    2: df_['col2'].dtype, 3: df_['col2'].dtype,}),
        ('col1', 0, '>='), ('col1', 1, '<='),
        ('col2', 2, '>='), ('col2', 3, '<='),
        right_columns=['result'], how='left'
      )

或者使用MultiIndex为IntervalIndex:

import numpy as np

a = np.array(ls).T

idx = (pd.MultiIndex
         .from_arrays([pd.IntervalIndex.from_arrays(a[0], a[1]),
                       pd.IntervalIndex.from_arrays(a[2], a[3])])
      )

df_['result'] = (pd.Series(a[4], index=idx)
                   .reindex(zip(df_['col1'], df_['col2']))
                   .values
                )

输出:

   col1  col2  result
0   1.1    11     5.0
1   3.5    35    10.0
2   5.4    44     NaN
3   4.1    41     NaN

Python相关问答推荐

我在使用fill_between()将最大和最小带应用到我的图表中时遇到问题

max_of_three使用First_select、second_select、

如何删除索引过go 的lexsort深度可能会影响性能?' &>

scikit-learn导入无法导入名称METRIC_MAPPING64'

Python键入协议默认值

如何在solve()之后获得症状上的等式的值

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

将pandas导出到CSV数据,但在此之前,将日期按最小到最大排序

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

在两极中过滤

Django admin Csrf令牌未设置

Python全局变量递归得到不同的结果

在代码执行后关闭ChromeDriver窗口

递归函数修饰器

如何在一组行中找到循环?

分解polars DataFrame列而不重复其他列值

TypeError:';Locator';对象无法在PlayWriter中使用.first()调用

上传文件并使用Panda打开时的Flask 问题

正在try 让Python读取特定的CSV文件

使用xlsxWriter在EXCEL中为数据帧的各行上色