python - 清理Python中的城市名称

标签 python pandas data-cleaning city

在数据框中,有一个“城市”列,其中包含不同的城市名称以及各种格式/拼写错误。以下是该列中的唯一值:

array(['somerville', 'hyde park', 'lexington', 'brookline', 'wellesley',
       'dover ', 'newton', 'westford', 'boston', 'needham', 'arlington',
       'wayland', 'waltham', 'cambridge', 'chestnuthill', 'salisbury ',
       'waban', 'weston', 'neeham', 'auburndale', 'belmont', 'allston',
       'auberdale', 'bedford', 'dover', 'lawrence', 'wilmington',
       'woburn', 'braintree', 'acton', 'winchester', 'middleton',
       'west newton', 'watertown', 'newton center', 'northfield',
       'roslindale', 'westwood', 'groton', 'natick', 'concord',
       'chestnut hill', 'westborough', 'sudbury', 'sherborn', 'quincy',
       'burlington', 'andover', 'littleton', 'stoughton'], dtype=object)

我只想使用映射清理四个城市名称,并保持其他城市名称不变。

我使用了下面的代码:

cities_names = (('Newton', ['west newton', 'newton center', 'chestnut hill', 'chestnuthill', 'waban', 'auberdale', 'auburndale']),
              ('Dover', ['dover ']), 
              ('Needham', ['neeham']), 
              ('Wellesley', ['wellesly']))

cities_map = {y:x[0] for x in cities_tup for y in x[1]}

df_MA.City = df_MA.City.map(cities_map)
df_MA.City.unique()

但输出是: array([nan, 'Dover', 'Newton', 'Needham'], dtype=object)

所以基本上,它将所有其他城市名称更改为 nan,这不是我想要的。还有其他方法或包来清理城市名称吗?

最佳答案

使用replace :

df_MA['City'] = df_MA['City'].replace(cities_map)

或者将mapfillna结合起来:

df_MA['City'] = df_MA['City'].map(cities_map).fillna(df_MA['City'])

注意。不要分配给 df_MA.City,始终使用方括号表示法:df_MA['City']

关于python - 清理Python中的城市名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75807831/

相关文章:

r - 如何从数据框中删除某些条件

python - 尝试使用 DockerFile 创建 Docker 容器时遇到以下错误 -> "error from sender: open .Trash: operation not permitted"

python - 在 Flask 应用程序的后台运行一个 scrapy 蜘蛛

python - 加速在给定范围内查找倍数的算法

python - 如何使用 Pandas 填充范围内的缺失值?

python - Pandas - 从列中的 float 中删除字符串

python - 如何在 Pandas Dataframe 中合并多个具有相似名称的列而不丢失数据

python - 使用 lxml 有效地计算非常大的 XML 文档中的元素

python - 如何获取数据框中某个值的列名

python - 防止 Pandas 将 "NA"读取为 NaN