pandas 选择查询在元组列中的行 [英] Pandas select rows where query is in column of tuples

查看:73
本文介绍了 pandas 选择查询在元组列中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中一列包含元组:

I have a dataframe in which one column contains tuples:

df = pd.DataFrame({'a':[1,2, 3], 'b':[(1,2), (3,4), (0,4)]})

   a       b
0  1  (1, 2)
1  2  (3, 4)
2  3  (0, 4)



<我想选择我提供的元素在元组中的行。

I would like to select the rows where an element I provide is in the tuple.

例如,返回元组中4的行,则预期结果将是:

For example, return rows where 4 is in a tuple, expect outcome would be:

   a       b
1  2  (3, 4)
2  3  (0, 4)

我尝试过:

print(df[df['b'].isin([4])]

但这会返回一个空数据框:

But this returns an empty dataframe:

Empty DataFrame
Columns: [a, b]
Index: []


推荐答案

您需要应用 code>:

You need apply with in:

print(df[df['b'].apply(lambda x: 4 in x)])
   a       b
1  2  (3, 4)
2  3  (0, 4)

这篇关于 pandas 选择查询在元组列中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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