Python 如何检查数据帧的每一行中是否有一个单词

Python 如何检查数据帧的每一行中是否有一个单词,python,pandas,Python,Pandas,我有一个熊猫数据框,其中有一列指定给城镇名称。在每个城镇名称后,我添加新南威尔士州一词,例如悉尼将成为新南威尔士州悉尼。然而,这意味着即使一个城镇已经编写了新南威尔士州,脚本也会再次添加该城镇,例如,新南威尔士州纳拉拉市将成为新南威尔士州纳拉拉市。如何检查名称是否已包含NSW,并且仅在NSW不存在时添加字符串。以下是我目前的代码: #Adds "NSW" to the end of each town in the dataframe and then adds these

我有一个熊猫数据框,其中有一列指定给城镇名称。在每个城镇名称后,我添加新南威尔士州一词,例如悉尼将成为新南威尔士州悉尼。然而,这意味着即使一个城镇已经编写了新南威尔士州,脚本也会再次添加该城镇,例如,新南威尔士州纳拉拉市将成为新南威尔士州纳拉拉市。如何检查名称是否已包含NSW,并且仅在NSW不存在时添加字符串。以下是我目前的代码:

#Adds "NSW" to the end of each town in the dataframe and then adds these changes to to the csv
df['FullAddress'] = df['FullAddress'] + ' NSW'
print(df)
df.to_csv('latLongTest.csv', index=False)
输出:

  FullAddress
0  Sydney NSW
1  Sydney NSW
2  Narara NSW
3  Narara NSW
0    Sydney NSW
1    Narara NSW
dtype: object

我个人的偏好是通常使用np。在这种情况下:

df['FullAddress'] = np.where((df['FullAddress'].str.endswith(' NSW')), df['FullAddress'], df['FullAddress'] + ' NSW')
它是矢量化的,类似于excel if语句IFCONDITION、THEN、ELSE。

使用pandas.Series.where和pandas.Series.str.endswith:

输出:

  FullAddress
0  Sydney NSW
1  Sydney NSW
2  Narara NSW
3  Narara NSW
0    Sydney NSW
1    Narara NSW
dtype: object