I am trying to use vectorization on a pandas dataframe to create a new column. The dataframe is fairly huge(millions of records). I am showing a dummy example here. I am showing a non vecotorised version which works but is not very efficient. I am trying to implement the vectorised version while using the function(the actual function is fairly complicated than the one shown here).
import pandas as pd
import numpy as np
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
def test(row):
if row['color'] =='green':
value='Green'
elif row['color'] =='red':
value=row['Type']
else:
value=row['Set']
return value
def test1(s,t,c):
if c =='green':
value='Green'
elif c =='red':
value=t
else:
value=s
return value
df['new_color']=df.apply(test,axis=1)
#df['new_color']=test1(df.Set,df.Type,df.color)
print(df)
Set Type color new_color
0 Z A green Green
1 Z B green Green
2 X B red B
3 Y C red C
Any help would be appreciated.