python - 按参数列表过滤数据帧

标签 python pandas

得到一个像这样的数据框:

pd.DataFrame({"type":["type1","type1","type1","type2","type2","type2","type1/type2","type1/type2","type1/type2"],
                    "id": [1,2,3,1,2,3,1,2,3],
                    "values":[1,np.nan,7,np.nan,5,np.nan,1,1,1]})

:

<表类=“s-表”> <标题> 类型 id 值 <正文> 类型1 1 1 类型1 2 NaN 类型1 3 7 类型2 1 NaN 类型2 2 5 类型2 3 NaN 类型1,类型2 1 1 类型1,类型2 2 1 类型1,类型2 3 1

我有一个像这样的“指南”(带有它们对应的 id 的类型):

type1 = [1,3]
type2 = [2,3]
type1,type2 = [1,2,3]

我想根据此列表过滤行(您可以看到有两种可能的情况:需要过滤 type1-id2 = NaN,但 type2-id3=NaN - 是一个有效值)

我怎样才能以最好的方式执行此操作?事实上,我有更大的 table 和更多的指南列表。

最佳答案

我建议创建字典,然后使用np.logical_or.reduce进行选择通过字典中的值循环 Series.eq对于 ==Series.isin如需查看成员(member)资格,请最后发送至 boolean indexing :

d = {}
d['type1'] = [1,3]
d['type2'] = [2,3]
d['type1/type2'] = [1,2,3]
print (d)
{'type1': [1, 3], 'type2': [2, 3], 'type1/type2': [1, 2, 3]}

m = np.logical_or.reduce([df['type'].eq(k) & df['id'].isin(v) for k, v in d.items()])

df = df[m]
print (df)
          type  id  values
0        type1   1     1.0
2        type1   3     7.0
4        type2   2     5.0
5        type2   3     NaN
6  type1/type2   1     1.0
7  type1/type2   2     1.0
8  type1/type2   3     1.0

另一种方法是创建新的 DataFrame 并合并所有与原始数据相交的列,这里是 typeid 列:

d = {}
d['type1'] = [1,3]
d['type2'] = [2,3]
d['type1/type2'] = [1,2,3]
print (d)

df1 = pd.DataFrame([(k, x) for k, v in d.items() for x in v], columns=['type','id'])
print (df1)
          type  id
0        type1   1
1        type1   3
2        type2   2
3        type2   3
4  type1/type2   1
5  type1/type2   2
6  type1/type2   3

df = df.merge(df1)
print (df)
          type  id  values
0        type1   1     1.0
1        type1   3     7.0
2        type2   2     5.0
3        type2   3     NaN
4  type1/type2   1     1.0
5  type1/type2   2     1.0
6  type1/type2   3     1.0

关于python - 按参数列表过滤数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66964820/

相关文章:

python - Django JOIN 将列重命名为查询集

python - 更改 pandas 数据帧多重索引中的值

python - 在 python 中使用 geopandas 将数据帧保存到 shapefile 会引发 bool 的 ValueError

excel - 使用 Pandas 执行左搜索功能

python - 在 Pandas 中移动窗口以检查特定范围值

python - 在 python 中的函数中使用 __import__() 函数

python - 有人可以为 Twitter 状态更新提供一个简单的 Python 示例吗?

python - 如何在 Django 中为第 3 方 REST 服务进行分页/分页

python - pandas 不同列中唯一值的频率

python - 在 CSV 文件中查找主键候选人的最快方法?