如何解决获取位置字符串的最后一个单词,特殊情况除外,例如“纽约”,“北达科他州”,“南卡罗来纳州”等
我正在尝试从pandas数据框创建一个新字段。该字段为“位置”,其中包含城市和州信息。我使用了str.split().str[-1]
函数来获取位置的最后一个字,通常是全州名称。
问题是像“北卡罗莱纳州”这样的州变成了“卡罗莱纳州”。我想考虑一些特殊情况,例如.str[-2]
=“北”或“新”或“南”或“西”。
这是我的代码示例:
df["state"] = df.location.str.split().str[-1]
print(df.state.value_counts().reset_index())
这是输出:
index state
0 california 59855
1 york 17
2 illinois 8
3 massachusetts 5
您会看到“纽约”应该是“纽约”。
我想我应该为location字段编写一个函数,如下所示:
def get_location(x):
if x.str.split().str[-2] in ["new","north","south","west"]:
return x.str.split().str[-2:]
else:
return x.str.split().str[-1]
这里的问题是调用get_location(df.location)
时收到以下错误消息:
“系列的真值不明确。请使用a.empty,a.bool(),a.item(),a.any()或a.all()。”
我在这里正确吗?我该怎么做才能使新的df.state字段返回如下输出:
index state
0 california 59855
1 new york 17
2 illinois 8
3 massachusetts 5
4 north corolina 3
谢谢!
解决方法
您可以使用split方法计算字符串的长度,如下所示:
# Dataframe dummy from your Data:
your_df = pd.DataFrame({'location': ['New York','North Carolina','South Illinois','Texas','Florida'],'another_field': [1000,2000,3000,4000,5000]})
# You verify the count of strings,if there are two or more,then you return full string.
your_df['state'] = your_df['location'].apply(lambda your_location: your_location if len(your_location.split(" ")) > 1 else your_location.split(" ")[-1])
your_df
输出:
location another_field state
0 New York 1000 New York
1 North Carolina 2000 North Carolina
2 South Illinois 3000 South Illinois
3 Texas 4000 Texas
4 Florida 5000 Florida
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。