如何在数据框上只保留具有特定文本的“单元格”?

2024-04-19 12:05:00 发布

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

我想知道是否可以只在数据框中保留具有特定文本的“单元格”,例如,如果我有以下数据框:

import pandas as pd
import numpy as np


df = pd.DataFrame(np.array([['12hello2', '12hey2', 'hello', '12hey2', '1hello'], ['12hey2', '12hey2', 'hello', '1hello', '1hello'], ['12hey2', '12hey2', 'hello', '1hello', '1hello']]),
                   columns=['a', 'b', 'c','d','e'])

除了包含字符串“hello”的“cells”之外,我如何删除所有内容?我知道如何对特定列或特定行执行此操作,但不知道如何对这两个行执行此操作,因此只剩下字符串中包含“hello”的实例


Tags: columns数据字符串文本importnumpyhellodataframe
3条回答

我能想到的最简单的方法是使用apply按列过滤,然后where屏蔽:

df.where(df.apply(lambda x: x.str.contains('hello')))

输出:

          a    b      c       d       e
0  12hello2  NaN  hello     NaN  1hello
1       NaN  NaN  hello  1hello  1hello
2       NaN  NaN  hello  1hello  1hello

使用replace

df[df.replace('.*hello.*', 'hello', regex=True).eq('hello')]

          a    b      c       d       e
0  12hello2  NaN  hello     NaN  1hello
1       NaN  NaN  hello  1hello  1hello
2       NaN  NaN  hello  1hello  1hello
​

stack/unstack

df[df.stack().str.contains('hello').unstack()]

          a    b      c       d       e
0  12hello2  NaN  hello     NaN  1hello
1       NaN  NaN  hello  1hello  1hello
2       NaN  NaN  hello  1hello  1hello

类似于replace

df.replace({"^(.(?<!hello))*?$":np.nan},regex=True)
          a   b      c       d       e
0  12hello2 NaN  hello     NaN  1hello
1       NaN NaN  hello  1hello  1hello
2       NaN NaN  hello  1hello  1hello

相关问题 更多 >