gpt4 book ai didi

Python:如果行中只有 1 个单词,则替换数据框/列中的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 08:30:08 25 4
gpt4 key购买 nike

我有相当困惑的数据 我正在尝试用 '' 或空字符串替换可能只包含 1 个单词或字符串的行。

原始数据如下:

df = pd.DataFrame({'some_text': [
'I enjoy read Mark Twain\'s Books',
'Library is very useful',
'/',
'\\',
'/ /',
'',
'I enjoy read Mark Twain\'s Books',
'an',
'the',
'Books are interesting'
]})

我试过这个:(这是删除行)。我不想删除行只是替换它。

count = df['some_text'].str.split().str.len()
df[~(count==1)]

需要的最终输出:

I enjoy read Mark Twain's Books
Library is very useful


/ /

I enjoy read Mark Twain's Books


Books are interesting

最佳答案

你可以在这里使用一个简单的正则表达式:

df['new_text'] = df['some_text'].str.replace('^\S+$','');
>>> df
some_text new_text
0 I enjoy read Mark Twain's Books I enjoy read Mark Twain's Books
1 Library is very useful Library is very useful
2 /
3 \
4 / / / /
5
6 I enjoy read Mark Twain's Books I enjoy read Mark Twain's Books
7 an
8 the
9 Books are interesting Books are interesting

关于Python:如果行中只有 1 个单词,则替换数据框/列中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53599329/

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