将所有城市名称更改为一个通用名称。
City b c
0 New york 1 1
1 New York 2 2
2 N.Y. 3 3
3 NY 4 4
他们称其为纽约市,但是python将它们视为独立的实体,因此我将其全部更改为一个。
df["City"] = df["City"].replace({"N.Y.":"New york", "New York": "New york", "NY": "New york"})
在此之后,我需要检查是否涵盖了纽约的所有变化,为此我创建了一个函数
def universal_ok(universal_name):
count = 0
for c in df.City:
if c == universal_name:
count += 1
# This only works when column consists of only one type of city
if count == len(df.City):
return "Yes all names are formatted correctly"
else:
return f"there are {len(df.City) - count} names that need to be changed"
universal_ok("New york")
但是问题是当一列中有多个城市时该怎么办
City b c
0 New york 1 1
1 New York 2 2
2 N.Y. 3 3
3 NY 4 4
4 Toronto 3 2
5 TO 3 2
6 toronto 3 2
有没有办法将每个城市更改为通用名称?