根据布尔值列表返回数据框子集 [英] Return dataframe subset based on a list of boolean values

查看:71
本文介绍了根据布尔值列表返回数据框子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据值列表对数据框进行切片,我将如何处理?

I'm trying to slice a dataframe based on list of values, how would I go about this?

说我有一个表达式或列表l = [0,1,0,0,1,1,0,0,0,1]

Say I have an expression or a list l = [0,1,0,0,1,1,0,0,0,1]

当表达式/列表中的对应值为1时,如何返回数据帧df中的那些行?在此示例中,我将包括index为1、4、5和9的行.

How to return those rows in a dataframe, df, when the corresponding value in the expression/list is 1? In this example, I would include rows where index is 1, 4, 5, and 9.

推荐答案

您可以在此处使用屏蔽:

You can use masking here:

df[np.array([0,1,0,0,1,1,0,0,0,1],dtype=bool)]

因此,我们构造一个包含true和false的布尔数组.数组为True的每个地方都是我们选择的一行.

So we construct a boolean array with true and false. Every place where the array is True is a row we select.

请注意,我们不会进行 not 过滤.为了检索结果,您必须将结果分配给(可选的)变量:

Mind that we do not filter inplace. In order to retrieve the result, you have to assign the result to an (optionally different) variable:

df2 = df[np.array([0,1,0,0,1,1,0,0,0,1],dtype=bool)]

这篇关于根据布尔值列表返回数据框子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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