gpt4 book ai didi

python将列中的字符串重命名为指定字符串

转载 作者:行者123 更新时间:2023-12-01 03:02:28 25 4
gpt4 key购买 nike

我有一列包含许多不同的字符串,我想要做的就是将我指定的所有字符串重命名为一个字符串,以便它们都具有相同的字符串。所以我的数据框看起来像这样:

          My_strings
1 I bumped my knee because I fell
2 I fell off my bike but I had a helmet
3 I am alright I just need to be alert
4 If I fall I will get back up

所以在我的专栏 My_strings 中说我想查找包含特定单词的句子。

df.loc[df.T_L_DESC.str.contains("fell|fall|fallen", na=False), 'Slippery'] = df.T_L_DESC

我正在寻找的具体单词是“fell|fall|fallen”,一旦在我的专栏的句子中找到这些单词,它们就会被分成另一个名为“Slip_Fall”的列

我想将所有包含这些单词的字符串重命名为一个特定的字符串。需要注意的一件事是,当我运行上面的代码时,它会使每个不包含其中指定的单词的句子 NaN 所以我的最终数据框将如下所示:

            My_strings                           Slippery
1 I bumped my knee because I fell Life_Lessons
2 I fell off my bike but I had a helmet Life_Lessons
3 NaN NaN
4 If I fall I will get back up Life_Lessons

所以我不想明显地将数据框中获得的 NaN 值更改为 Life_Lessons 我只想将包含关键字的句子更改为 Life_Lessons

提前致谢

最佳答案

一个简单的解决方案:

In [191]: df.loc[df.T_L_DESC.str.contains("fell|fall|fallen", na=False), 'Slippery'] = 'Life_Lessons'

In [192]: df
Out[192]:
T_L_DESC Slippery
0 I bumped my knee because I fell Life_Lessons
1 I fell off my bike but I had a helmet Life_Lessons
2 I am alright I just need to be alert NaN
3 If I fall I will get back up Life_Lessons

In [193]: df.loc[df.Slippery!='Life_Lessons', 'T_L_DESC'] = np.nan

In [194]: df
Out[194]:
T_L_DESC Slippery
0 I bumped my knee because I fell Life_Lessons
1 I fell off my bike but I had a helmet Life_Lessons
2 NaN NaN
3 If I fall I will get back up Life_Lessons

关于python将列中的字符串重命名为指定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43682830/

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