猿问

Pandas 中的类别值分配

在我的数据框中,我有两列。Emp_id 和城市。数据框的总大小为 320 万个,包含多个城市名称。数据框看起来像 -


emp_id         city

  2            New York

  3            Houston

  6            Dallas

  7            New York

  11           Dallas

  12           Austin

  13           San Jose

  14           Boston

  15           Boston

  16           Columbus

  24           Austin

  30           Austin

我的最终输出看起来像 -


emp_id         city              present

  2            New York             1

  3            Houston              0

  6            Dallas               1

  7            New York             1

  11           Dallas               1

  12           Austin               0

  13           San Jose             0

  14           Boston               1

  15           Boston               1

  16           Columbus             0

  24           Austin               0

  30           Austin               0

到目前为止我已经做了 -


df['present'] = np.where(df.loc[df['city'].isin(['New York','Dallas','Boston'])],1,0)

我只想将 3 个城市视为“1”,其余城市为“0”


喵喵时光机
浏览 221回答 1
1回答

慕容森

你可以做:df['present'] = np.where(df['city'].isin(['New York','Dallas','Boston']),1,0)
随时随地看视频慕课网APP

相关分类

Python
我要回答