First you can create a new column col2and update its values based on conditions:
df['col2'] = 'zzz'
df.loc[(df['col1'] > 0) & (df['col1'] <= 10), 'loc2'] = 'xxx'
df.loc[(df['col1'] > 10) & (df['col1'] <= 50), 'loc2'] = 'yyy'
print df
Output:
col1 col2
0 1 xxx
1 1 xxx
2 4 xxx
3 5 xxx
4 6 xxx
5 6 xxx
6 30 yyy
7 20 yyy
8 80 zzz
9 90 zzz
Alternatively, you can also apply a function based on a column col1:
def func(x):
if 0 < x <= 10:
return 'xxx'
elif 10 < x <= 50:
return 'yyy'
return 'zzz'
df['col2'] = df['col1'].apply(func)
and this will lead to the same exit.
The approach applyshould be preferred in this case, since it is much faster:
%timeit run()
%timeit df['col2'] = df['col1'].apply(func)
, DataFrame , (.. ) .