Pandas - 根据另一列(城市名称)创建一个新列(分行名称)

Pandas - Create a new column (Branch name) based on another column (City name)

我有以下 Python Pandas 数据框(8 行):

City Name
     
New York
Long Beach
Jamestown
Chicago
Forrest Park
Berwyn
Las Vegas
Miami

我想添加一个基于城市名称的新列(分行名称),如下所示:

City Name       Branch Name

New York        New York
Long Beach      New York
Jamestown       New York
Chicago         Chicago
Forrest Park    Chicago
Berwyn          Chicago
Las Vegas       Las Vegas
Miami           Miami 

我该怎么做?

您可以使用 .map()。不在字典中的城市名称将被保留。

df["Branch Name"] = df["City Name"].map({"Long Beach":"New York",
                                         "Jamestown":"New York",
                                         "Forrest Park":"Chicago",
                                         "Berwyn":"Chicago",}, na_action='ignore')
df["Branch Name"] = df["Branch Name"].fillna(df["City Name"])