pandas df subset by string列中的列表

2024-04-26 17:44:51 发布

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

我有一个复杂的,大熊猫数据帧,有一列X,可以包含一个列表或一个列表列表。我很好奇这个解决方案是否适用于任何内容,因此我给出了一个模拟示例,其中一个X元素也是一个字符串:

df1 = pd.DataFrame({
    'A': [1, 1, 3], 
    'B': ['a', 'e', 'f'], 
    'X': ['something', ['hello'], [['something'],['hello']]]}
)

我想得到这个数据帧的子集df2,其中的X列包含子字符串“hello”,当其中的任何内容被作为字符串读取时。在

^{pr2}$

我尝试过str()和。结构包含,apply,map,.find(),list comprehensions,如果不进入循环(相关问题herehere),似乎什么都不起作用。我错过了什么?在


Tags: 数据字符串元素示例内容hellodataframe列表
3条回答

str.contains之前添加astype

df1[df1.X.astype(str).str.contains('hello')]
Out[538]: 
   A  B                       X
1  1  e                 [hello]
2  3  f  [[something], [hello]]

借用@wimhttps://stackoverflow.com/a/49247980/2336654

最普遍的解决方案是允许任意嵌套的列表。另外,我们可以关注字符串元素是否相等,而不是包含。在

# This import is for Python 3
# for Python 2 use `from collections import Iterable`
from collections.abc import Iterable

def flatten(collection):
    for x in collection:
        if isinstance(x, Iterable) and not isinstance(x, str):
            yield from flatten(x)
        else:
            yield x

df1[df1.X.map(lambda x: any('hello' == s for s in flatten(x)))]

   A  B                       X
1  1  e                 [hello]
2  3  f  [[something], [hello]]

所以现在如果我们把它复杂化

^{pr2}$

我们的过滤器不抓取hello world,而是抓取非常嵌套的hello

df1[df1.X.map(lambda x: any('hello' == s for s in flatten(x)))]

   A  B                       X
1  1  e                 [hello]
2  3  f  [[something], [hello]]
4  7  s     [[[[[['hello']]]]]]

你可以用np.拉威尔()展开嵌套列表并在运算符中使用

df1[df1['X'].apply(lambda x: 'hello' in np.ravel(x))]

    A   B   X
1   1   e   [hello]
2   3   f   [[something], [hello]]

相关问题 更多 >