I have pandas dataframe like this
JavaScript
x
9
1
ID Phone ex
2
3
0 1 5333371000 533
4
1 2 5354321938 535
5
2 3 3840812 384
6
3 4 5451215 545
7
4 5 2125121278 212
8
9
For example if “ex” start to 533,535,545 new variable should be :
Sample output :
JavaScript
1
8
1
ID Phone ex iswhat
2
3
0 1 5333371000 533 personal
4
1 2 5354321938 535 personal
5
2 3 3840812 384 notpersonal
6
3 4 5451215 545 personal
7
4 5 2125121278 212 notpersonal
8
How can i do that ?
Advertisement
Answer
You can use np.where
:
JavaScript
1
11
11
1
df['iswhat'] = np.where(df['ex'].isin([533, 535, 545]), 'personal', 'not personal')
2
print(df)
3
4
# Output
5
ID Phone ex iswhat
6
0 1 5333371000 533 personal
7
1 2 5354321938 535 personal
8
2 3 3840812 384 not personal
9
3 4 5451215 545 personal
10
4 5 2125121278 212 not personal
11
Update
You can also use your Phone
column directly:
JavaScript
1
3
1
df['iswhat'] = np.where(df['Phone'].astype(str).str.match('533|535|545'),
2
'personal', 'not personal')
3
Note: If Phone
column contains strings you can safely remove .astype(str)
.