I have a pandas dataframe which looks like this:
Input dataframe:
A B C
0 m h c
1 l c m
2 h m l
3 c l h
4 m c m
I want to replace each occurrence of each l,m,h,and c values with floating point numbers in a given range. The range of values for each string is as follows:
Range:
l: 0.0 - 0.25
m: 0.25 - 0.5
h: 0.5 - 0.75
c: 0.75 - 1.0
Each occurrence should have a value in the given range but it should not repeat. The sample output dataframe should look like this after transformation:
Output dataframe:
A B C
0 0.31 0.51 0.76
1 0.12 0.56 0.28
2 0.61 0.35 0.21
3 0.8 0.16 0.71
4 0.46 0.72 0.37
I have tried one approach using transform. But its not fully working as values are repeated in the columns:
def _foo(col):
w = {'l': np.random.uniform(0.0,0.25),
'm':np.random.uniform(0.25,0.5),
'h': np.random.uniform(0.5,0.75),
'c':np.random.uniform(0.75,1.0)}
col = col.replace(w)
return col
df = df.transform(_foo)
If I use apply method then also the same problem will happen and values are repeated along the rows. It also doesnt have good performance as the actual dataframe has 50-60 thousand rows. So the apply will run for that many times.
def _bar(row):
w = {'l': np.random.uniform(0.0,0.25),
'm':np.random.uniform(0.25,0.5),
'h': np.random.uniform(0.5,0.75),
'c':np.random.uniform(0.75,1.0)}
row= row.replace(w)
return row
df = df.apply(_bar, axis=1)
Any suggestions on how to do this efficiently in pandas?
