我有这样的熊猫数据
ID Phone ex
0 1 5333371000 533
1 2 5354321938 535
2 3 3840812 384
3 4 5451215 545
4 5 2125121278 212例如,如果"ex“开始使用533,535,545个新变量,则应:
样本输出:
ID Phone ex iswhat
0 1 5333371000 533 personal
1 2 5354321938 535 personal
2 3 3840812 384 notpersonal
3 4 5451215 545 personal
4 5 2125121278 212 notpersonal我怎么能这么做?
发布于 2022-03-11 07:05:36
您可以使用np.where
df['iswhat'] = np.where(df['ex'].isin([533, 535, 545]), 'personal', 'not personal')
print(df)
# Output
ID Phone ex iswhat
0 1 5333371000 533 personal
1 2 5354321938 535 personal
2 3 3840812 384 not personal
3 4 5451215 545 personal
4 5 2125121278 212 not personal更新
还可以直接使用Phone列:
df['iswhat'] = np.where(df['Phone'].astype(str).str.match('533|535|545'),
'personal', 'not personal')注意:如果Phone列包含字符串,则可以安全地删除.astype(str)。
发布于 2022-03-11 07:05:14
我们可以使用np.where和str.contains
df["iswhat"] = np.where(df["ex"].str.contains(r'^(?:533|535|545)$'),
'personal', 'notpersonal')https://stackoverflow.com/questions/71434729
复制相似问题