gpt4 book ai didi

python - 使用列表理解根据字符长度从系列中删除字符串Python

转载 作者:行者123 更新时间:2023-12-01 06:32:19 24 4
gpt4 key购买 nike

我在 df 数据框中有这个系列:

column1                     column2   column3
needs n before mi toilets 2013 sport

我想在 column1 中删除字符数低于 4 次的字符串,以便我的数据框如下所示:

column1               column2   column3
needs before toilets 2013 sport

我尝试使用以下代码列出简单的 for 循环:

for i in df['column1'].str.split():
for j in i:
if len(j) < 4:
df['column1'].drop(j)

但我收到错误消息:

"['n'] not found in axis"

我还尝试简化代码以列表理解,但到目前为止我还没有得到好的代码。这是我尝试这样做的但使用 print (j) 作为我的输出:

 [print(j) for i in df['column1'].str.split() for j in df['column1'] if len(j) < 4]

我没有得到该代码的任何返回。

有人知道为什么吗?谢谢

最佳答案

使用pandas.Series.str.findalljoin:

df['column1'].str.findall('\w{4,}').str.join(' ')

输出:

0    needs before toilets
Name: column1, dtype: object

关于python - 使用列表理解根据字符长度从系列中删除字符串Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59837071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com