过滤 pandas 数据帧列时如何使用.le()和.ge()? [英] How to use .le() and .ge() when filtering pandas data frame columns?

查看:47
本文介绍了过滤 pandas 数据帧列时如何使用.le()和.ge()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例熊猫数据框:

Here is an example pandas DataFrame:

import pandas as pd
import numpy as np

data = {"first_column": ["item1", "item2", "item3", "item4", "item5", "item6", "item7"],
        "second_column": ["cat1", "cat1", "cat1", "cat2", "cat2", "cat2", "cat2"],
        "third_column": [5, 1, 8, 3, 731, 189, 9]}

df = pd.DataFrame(data)

df
     first_column second_column  third_column
0        item1          cat1             5
1        item2          cat1             1
2        item3          cat1             8
3        item4          cat2             3
4        item5          cat2           731
5        item6          cat2           189
6        item7          cat2             9

我想根据10 =<过滤"第三列x = <1000.

I would like to "filter" the third column based on 10 =< x =<1000.

如果我的结果大于或等于10,则为:

If I do greater than or equal to 10, this is:

df['greater_than_ten'] = df.third_column.ge(10).astype(np.uint8)

如果我的成绩少于1000,则为:

If I do less than 1000, it is:

df['less_than_1K'] = df.third_column.le(1000).astype(np.uint8)

但是我不能同时执行这些操作,即

but I cannot do these operations simultaneously, i.e.

df['both'] = df.third_column.le(1000).ge(10).astype(np.uint8)

我也不能按顺序尝试这些操作.

Nor could I try these operations sequentially.

如何一起使用.ge().le()?

推荐答案

您可以使用

You can use between() instead for your Series of interest.

df['both'] = df.third_column.between(10, 1000).astype(np.uint8)

屈服

>>> df

  first_column second_column  third_column  both
0        item1          cat1             5     0
1        item2          cat1             1     0
2        item3          cat1             8     0
3        item4          cat2             3     0
4        item5          cat2           731     1
5        item6          cat2           189     1
6        item7          cat2             9     0

这篇关于过滤 pandas 数据帧列时如何使用.le()和.ge()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆