Python:基于多个动态列值过滤数据帧行

2024-10-02 16:30:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据列值列表筛选数据帧的行。问题是,我有动态输入的列的长度,到目前为止,我已经尝试过了,但这并不能达到我的目的。在

>>>df
    a      b
0  jdfb  sdvkb

如果我必须同时搜索这两列。也就是说,如果a='jdfb'和{},那么我需要返回1。在

我将动态创建的搜索列存储在列表变量fields中,值也存储在另一个列表变量“matchlist”中。在

^{pr2}$

方法1我尝试了这个方法,它奏效了:

>>> df[fields].isin(matchlist)
    a     b
0  True  True

这很好。这正是我想要的。但当我尝试下一个查询时,这不是我想要的,因为它不应该起作用:

>>> df[fields].isin(matchlist)
    a     b
0  True  True

这种方法的问题是列应该按照方法1中指定的顺序匹配,而不是按照我尝试的下一种方式。我有什么办法可以做到这一点吗?在


Tags: 数据方法目的truefieldsdf列表动态
1条回答
网友
1楼 · 发布于 2024-10-02 16:30:30

生成两个独立的布尔索引并将它们组合起来可能更容易。在

>>> import pandas as pd
>>> 
>>> #create the mapping of desirable values
... desirable = ['a','b']
>>> 
>>> #create data where some rows match the conditions
... data = [desirable,desirable[::-1],desirable, desirable, desirable[::-1]]
>>> df = pd.DataFrame(data, columns = ['first','second'])
>>> 
>>> #Rows 0, 2, and 3 match our conditions
... df
  first second
0     a      b
1     b      a
2     a      b
3     a      b
4     b      a
>>> 
>>> #create a boolean mask for rows that match our conditions
... conditions = (df['first'] == desirable[0]) & (df['second'] == desirable[1])
>>> 
>>> #we can now use this boolean mask to get the desired rows
... df[conditions]
  first second
0     a      b
2     a      b
3     a      b
>>> 

相关问题 更多 >