Pandas dataframe:使用条件和切片字符串创建新列



我有这样一段代码,它创建了一个新的数据框列,首先使用一个条件,然后用一个固定的切片索引(0,5)切片一些字符串:

df.loc[df['operation'] == 'dividend', ['order_adj']] = df['comment'].str.slice(0, 5)

但是,不是有一个固定的切片索引,我需要在这段代码的最后使用str.find(),在df['comment']上有一个动态的切片索引,基于它的字符。

当我通过广播创建一个新的专栏时,我找不到正确的sintaxe来使用str.find('some_string')inside str.slice()。谢谢。

使用split:

df['comment'].str.split("some_string").str[0]

或使用regex的选项(将捕获组移动到您想要的包含/排他位置):

pandas.Series.str.extract("(.*?)some_string")
pandas.Series.str.extract("(.*?some_string)")

最新更新