【问题标题】:Subset data using a tuple of conditions in Python在 Python 中使用条件元组对数据进行子集化
【发布时间】:2023-04-04 14:08:01
【问题描述】:

我有一个输入数据框和一个元组列表。使用我将用来过滤数据框的元组列表。元组的结构如下:

    [(column_name1, min_value1, max_value1),(column_name2, min_value2, max_value2),....,(column_namen, min_valuen, max_valuen)]

如何在知道给定数据帧的最大和最小条件的情况下遍历元组列表?给定的 column_names 与数据框中的列名匹配,因此无需确保该列存在。

谢谢!

【问题讨论】:

  • “我如何在知道数据帧的最大和最小条件的情况下遍历元组列表”你是什么意思?是这个问题吗?如果是,请解释一下。
  • @Jab 使用我将用来过滤数据框的元组列表。 OP 希望根据特定列过滤结果,并且可能在提供的最大值和最小值之间?
  • 您想如何精确过滤数据?你有一些示例输入和输出吗?
  • 大家好,感谢您的帮助!我能够找出答案。谢谢!

标签: python pandas tuples filtering


【解决方案1】:

尝试使用pd.Series.between 运算符:

import pandas as pd
import random
df = pd.DataFrame([{k: random.randint(0, 100) for k in 'abcde'} for i in range(10)])
df
     a   b   c   d   e
0   35  60  24  13  27
1   86  11  18  60  96
2   61  68  94   9  68
3   67   2  75  47   9
4   79  94   6  60   4
5   50  75  13  67  72
6  100   5  46  46  91
7   11  67  26  44  82
8   89   6   8  53  30
9   71  73  17   5  66


criteria = [('b', 4, 35), ('c', 20, 99)]

for col, _min, _max in criteria:
    # this is a series of type bool you can use
    # to filter your column
    mask = df[col].between(_min, _max)

    # this will get the values from that particular
    # column that satisfy the condition (condition is true)
    df[col][mask]

1    11
6     5
8     6
Name: b, dtype: int64


0    24
2    94
3    75
6    46
7    26
Name: c, dtype: int64

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2016-08-08
    • 1970-01-01
    相关资源
    最近更新 更多