基于现有列的条件创建新列的最简洁方法是什么?

What is the cleanest way to create a new column based on a conditional of an existing column?

在 pandas 中,我目前有一个包含一列字符串的数据框:{Urban, Suburban, Rural}。我想创建的列是第一列的条件(即城市、郊区、农村与相应的颜色相关联){珊瑚色、天蓝色、金色}

我尝试复制第一列然后使用 .replace 但我的新列现在似乎 return NaN 值而不是颜色。

new_column = merge_table["type"]
merge_table["color"] = new_column

color_df = merge_table["color"].replace({'Urban': 'Coral', 'Suburban': 'Skyblue', 'Rural': 'Gold'})



data = pd.DataFrame({'City Type': type,
                           'Bubble Color': color_df    
                          })
data.head()

你可以做到

 merge_table['New col']=merge_table["color"].replace({'Urban': 'Coral', 'Suburban': 'Skyblue', 'Rural': 'Gold'})

好的。将来,值得使用 'Code Samples' 键入代码,以便我们可以更轻松地查看您的代码。

很多方面都可以改进您的代码。首先,你在一行中完成所有事情:

merge_table["color"] = merge_table["type"].map(mapping_dictionary)

Series.map() 比 Series.replace() 快 4 倍左右供您参考。

还有其他提示:

  1. 永远不要使用类型作为变量名,使用更具体的东西,比如 city_type。 type 已经是标准的内置方法

    data = pd.DataFrame({'City Type': city_type, 'Bubble Color': color_df})
    
  2. 如果复制列,请使用:

    a_series = df['column_name'].copy()