我有這樣的熊貓資料框
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
我怎樣才能做到這一點 ?
uj5u.com熱心網友回復:
您可以使用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).
uj5u.com熱心網友回復:
我們可以np.where一起使用str.contains:
df["iswhat"] = np.where(df["ex"].str.contains(r'^(?:533|535|545)$'),
'personal', 'notpersonal')
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441274.html
