gpt4 book ai didi

python - 将指定的字符串分配到数据框中自己的列中

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

我想知道是否有可能做我想做的事。我现在正在使用

df.loc[df.T_LOSS_DESC.str.contains("slip", na=False)]

它找到 T_LOSS_DESC 列,然后在该列中的任何位置,其中包含特定单词(如“slip”)的地方都会返回这些行。我的第一个问题是是否可以将结果放在自己的列中?另外,如果是这样,他们是否要指定多个可能的关键字来查找?示例是

 df.loc[df.T_LOSS_DESC.str.contains("slip,Slip,Slipped", na=False)]

这可行吗?或者我只能使用一个参数?

我的数据框是什么样的:

         T_LOSS_DESC 
1 Bob was running and Slipped
2 Jeff got burnt by the sun
3 James went for a walk

我希望我的数据框看起来像的是,如果它在我正在查看的列中找到匹配项,我希望它将匹配项放在不同的列中。

所以我的最终数据框看起来像这样:

         T_LOSS_DESC                          Slippery
1 Bob was running and Slipped Bob was running and Slipped
2 Jeff got burnt by the sun
3 James went for a walk

因此,由于我的字符串中只有一个与我在该列中查找的字符串相匹配,因此它将将该匹配项放入名为 Slippery 的新列中

提前致谢。

最佳答案

IIUC:

In [95]: df['new'] = df.loc[df.T_LOSS_DESC.str.contains("slip|Slip|Slipped", na=False)]

In [96]: df
Out[96]:
T_LOSS_DESC new
0 Bob was running and Slipped Bob was running and Slipped
1 Jeff got burnt by the sun NaN
2 James went for a walk NaN

或者你可以这样做:

In [116]: df.loc[df.T_LOSS_DESC.str.contains("slip|Slip|Slipped", na=False), 'Slippery'] = df.T_LOSS_DESC

In [117]: df
Out[117]:
T_LOSS_DESC Slippery
0 Bob was running and Slipped Bob was running and Slipped
1 Jeff got burnt by the sun NaN
2 James went for a walk NaN

关于python - 将指定的字符串分配到数据框中自己的列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43665435/

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