列「郵便番号」が100以上209以下であれば1、でなければ0のフラグを付ける

投稿者: | 2022-06-10

<変更前df>

<変更後df>

# 方法1:内包表記(df['col'].str[:3]がポイント)
df['postal_flg'] = [1 if (int(i) >= 100) and (int(i) <= 209) else 0 for i in df['postal_cd'].str[:3]]
df
# 方法2:applyまたはmapを利用
df['postal_flg'] = df['postal_cd'].apply(lambda x: 1 if 100 <= int(x[0:3]) <= 209 else 0).rename('postal_flg')
df
# 方法3:numpyのwhere、betweenを利用
df['postal_flg'] = np.where(df['postal_cd'].str[0:3].astype(int).between(100, 209), 1, 0)
df