如果拆分后存在第二个字符串,则提取(get)第二个字符串,否则提取第一个字符串

2024-04-20 05:01:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据一个短语分割一组字符串,得到第二个元素。但是,在不能拆分字符串的情况下,我希望保留第一个元素。下面是一个显示我当前方法的示例,默认情况下,我总是提取第二个元素:

import pandas as pd
df = pd.DataFrame({"a" : ["this is a (test), it is", "yet another"]})
df["a"].str.split("\(test\)", 1).str[1]

如你所见,这(错误地)给了我

0    , it is
1        NaN
Name: a, dtype: object

而我想要的结果应该是

0     , it is
1    yet another
Name: a, dtype: object

Tags: 方法字符串nametest元素dfobjectis
1条回答
网友
1楼 · 发布于 2024-04-20 05:01:18

用原始列a添加^{}

df['b'] = df["a"].str.split("\(test\)", 1).str[1].fillna(df["a"])
#alternative
#df['b'] = df["a"].str.split("\(test\)", 1).str[1].combine_first(df["a"])
print (df)
                         a            b
0  this is a (test), it is      , it is
1              yet another  yet another

相关问题 更多 >