如何从数据集中的行中删除某些单词 - Pandas
How to remove certain words from rows in a dataset - Pandas
在我的数据集中,有一个名为 AdminRegion2 的列,它有数千个不同的值,每个值在不同的行中,它们都是美国的县。我需要从每个县名中删除某些单词,以便我可以 link 将数据集转换为 GeoJSON 文件。
有些县在名称“自治市镇、人口普查区或县”之后写有这些词。我需要从可能包含其中任何一个的每一行中删除所有三个词。所以它只是“Baldwin”
这是人口普查区的代码,我很累,但最后有人口普查区的所有县仍然有它。我不知道为什么它不起作用。
only_counties = usa_only[usa_only['AdminRegion2'].str.contains("", na = False)]
only_counties = only_counties['AdminRegion2'].str.strip().str.replace("Census Area", '')
only_counties.to_csv("counties_only.csv")
试试这个:
usa_only['AdminRegion2']=usa_only['AdminRegion2'].apply(lambda x: x.replace(' Borough', '').replace(' Census Area', '').replace(' County', ''))
我会使用:
only_counties = usa_only[usa_only['AdminRegion2'].str.contains("", na = False)].copy() # now only_counties is a sliced copy of usa_only, not a view
only_counties['AdminRegion2'] = only_counties['AdminRegion2'].str.replace(' County', '')
only_counties['AdminRegion2'] = only_counties['AdminRegion2'].str.replace(' Census Area', '')
only_counties['AdminRegion2'] = only_counties['AdminRegion2'].str.replace(' Borough', '')
这应该可以解决问题
在我的数据集中,有一个名为 AdminRegion2 的列,它有数千个不同的值,每个值在不同的行中,它们都是美国的县。我需要从每个县名中删除某些单词,以便我可以 link 将数据集转换为 GeoJSON 文件。
有些县在名称“自治市镇、人口普查区或县”之后写有这些词。我需要从可能包含其中任何一个的每一行中删除所有三个词。所以它只是“Baldwin”
这是人口普查区的代码,我很累,但最后有人口普查区的所有县仍然有它。我不知道为什么它不起作用。
only_counties = usa_only[usa_only['AdminRegion2'].str.contains("", na = False)]
only_counties = only_counties['AdminRegion2'].str.strip().str.replace("Census Area", '')
only_counties.to_csv("counties_only.csv")
试试这个:
usa_only['AdminRegion2']=usa_only['AdminRegion2'].apply(lambda x: x.replace(' Borough', '').replace(' Census Area', '').replace(' County', ''))
我会使用:
only_counties = usa_only[usa_only['AdminRegion2'].str.contains("", na = False)].copy() # now only_counties is a sliced copy of usa_only, not a view
only_counties['AdminRegion2'] = only_counties['AdminRegion2'].str.replace(' County', '')
only_counties['AdminRegion2'] = only_counties['AdminRegion2'].str.replace(' Census Area', '')
only_counties['AdminRegion2'] = only_counties['AdminRegion2'].str.replace(' Borough', '')
这应该可以解决问题