gpt4 book ai didi

python - python 将一列的括号中的字符串插入到另一列的字符串的开头

转载 作者:太空宇宙 更新时间:2023-11-03 20:26:29 25 4
gpt4 key购买 nike

我有一个如下所示的数据框:

Name    Country         (Title)
0 Elizabeth England (Queen of)
1 Jackson Pop (King of)
2 Trump USA (President of)
3 Macron France (President of)
4 Clinton USA None
5 Blair England None
6 Elvis RocknRoll (King of)

我想要得到的是以下内容:

 Name             Country                (Title)
0 Elizabeth Queen of England (Queen of)
1 Jackson King of Pop (King of)
2 Trump President of USA (President of)
3 Macron President of France (President of)
4 Clinton USA None
5 Blair England None
6 Elvis King of RocknRoll (King of)

我已经进行了多次尝试(包括使用正则表达式)。我已经尝试过下面的代码,它非常清晰,但也不起作用。

欢迎任何建议!

谢谢。

def extract(w):
begin = w.find('(')
if begin == -1:
return ''
begin += 1
end = w.find(')', begin)
if end == -1:
return w[begin:]
else:
return w[begin:end]
for i in range(len(table)):
if table['(Title)'][i] != None :
table['Country'][i] = extract(table['Title'[i]).str.cat(table['Country'].values.astype(str), sep='')
 Name             Country                (Title)
0 Elizabeth Queen of England (Queen of)
1 Jackson King of Pop (King of)
2 Trump President of USA (President of)
3 Macron President of France (President of)
4 Clinton USA None
5 Blair England None
6 Elvis King of RocknRoll (King of)

最佳答案

你可以使用这个:

df['new_country'] = df['(title)'].str[1:-1] + ' ' + df['country']
df.loc[pd.notna(df['(title)']), 'country'] = df['new_country']

关于python - python 将一列的括号中的字符串插入到另一列的字符串的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57777278/

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