小编Lok*_*esh的帖子

Python - 用正则表达式模式替换 DataFrame 中列表中的单词

我有以下列表和 DataFrame:

mylist = ['foo', 'bar', 'baz']
df = pd.DataFrame({'Col1': ['fooThese', 'barWords', 'baz are', 'FOO: not', 'bAr:- needed'],
                   'Col2': ['Baz:Neither', 'Foo Are', 'barThese', np.nan, 'but this is fine']})
Run Code Online (Sandbox Code Playgroud)

如果在 DataFrame 中找到,我想替换 mylist 中的字符串。我可以使用以下正则表达式模式替换一些:

pat = '|'.join([r'\b{}'.format(w) for w in mylist])
df2 = df.replace(pat, '', regex=True)
Run Code Online (Sandbox Code Playgroud)

但是,这并没有放置所有实例。我想要的输出如下:

    Col1     Col2
0   These    Neither
1   Words    Are
2   are      These
3   not      NaN
4   needed   but this is fine

Run Code Online (Sandbox Code Playgroud)

python regex replace pandas python-re

2
推荐指数
1
解决办法
435
查看次数

从嵌套列表中删除空子列表

我有以下嵌套列表:

mynestedlist = [[[], [], [], ['Foo'], [], []], [[], ['Bar'], [], []], ['FOO'], 'BAR']
Run Code Online (Sandbox Code Playgroud)

我想将它展平到最外面的项目,这会给我主列表中的 4 个项目。但是,我只想要带有文本的项目,并且想要删除空括号列表。

期望的输出:

mynestedlist = [[['Bar']], ['FOO'], 'BAR']
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

newlist = []
for i in mynestedlist:
    for sub in i:
        if sub != []:
            newlist.append(sub)
Run Code Online (Sandbox Code Playgroud)

但是,我得到以下输出:

[['Foo'], ['bar'], 'FOO', 'B', 'A', 'R']
Run Code Online (Sandbox Code Playgroud)

python nested list sublist python-3.x

1
推荐指数
1
解决办法
343
查看次数

标签 统计

python ×2

list ×1

nested ×1

pandas ×1

python-3.x ×1

python-re ×1

regex ×1

replace ×1

sublist ×1