在数据框中,有一个“城市”列,其中包含不同的城市名称以及各种格式/拼写错误。以下是该列中的唯一值:
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)
或者将map
和fillna
结合起来:
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/