gpt4 book ai didi

python - 如果分割后存在,则提取(获取)第二个字符串,否则首先提取

转载 作者:行者123 更新时间:2023-11-30 22:00:30 25 4
gpt4 key购买 nike

我想根据一个短语拆分一堆字符串并获取第二个元素。但是,在字符串无法拆分的情况下,我想保留第一个元素。这是一个显示我当前方法的示例,默认情况下我总是提取第二个元素:

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

最佳答案

添加Series.fillna与原始列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

关于python - 如果分割后存在,则提取(获取)第二个字符串,否则首先提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54304868/

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