So let's say I have something like this:~
A
v1
v2
v3
v3
v4
And i have list that's like this:
python_list_1 = ["v1","v2"]
python_list_2 = ["v3","v4"]
And now I want to make something along these likes:
df['A'] = np.where(df['B'] in python_list_1 , "XT")
df['A'] = np.where(df['B'] in python_list_2 , "AB")
A B
v1 XT
v2 XT
v3 AB
v3 AB
v4 AB
Any tips for a pandas newbie?
Use numpy.select
with isin
for conditions, also is possible set default
value if some value not matched both conditions:
print (df)
A
0 v1
1 v2
2 v3
3 v3
4 v4
5 v5
python_list_1 = ["v1","v2"]
python_list_2 = ["v3","v4"]
m1 = df['A'].isin(python_list_1)
m2 = df['A'].isin(python_list_2)
df['B'] = np.select([m1, m2], ["XT", "AB"], default=df['A'])
print (df)
A B
0 v1 XT
1 v2 XT
2 v3 AB
3 v3 AB
4 v4 AB
5 v5 v5
df['B'] = np.select([m1, m2], ["XT", "AB"], default='no match')
print (df)
A B
0 v1 XT
1 v2 XT
2 v3 AB
3 v3 AB
4 v4 AB
5 v5 no match
numpy alternative
with numpy.in1d
:
m1 = np.in1d(df['A'], python_list_1)
m2 = np.in1d(df['A'], python_list_2)
df['B'] = np.select([m1,m2],[ "XT", "AB"], default='no match')
print (df)
A B
0 v1 XT
1 v2 XT
2 v3 AB
3 v3 AB
4 v4 AB
5 v5 no match
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments