Rehan Azher
Rehan Azher

Reputation: 1340

Pandas Replace Values with Dictionary

I have a data frame with the below structure:

        Ranges  Relative_17-Aug  Relative_17-Sep  Relative_17-Oct
0   (0.0, 0.1]  1372             1583             1214
1   (0.1, 0.2]  440              337              648
2   (0.2, 0.3]  111              51               105
3   (0.3, 0.4]  33               10               19
4   (0.4, 0.5]  16               4                9
5   (0.5, 0.6]  7                7                1
6   (0.6, 0.7]  4                3                0
7   (0.7, 0.8]  5                1                0
8   (0.8, 0.9]  2                3                0
9   (0.9, 1.0]  2                0                1
10  (1.0, 2.0]  6                0                2

I am trying to replace column ranges with a dictionary using the below code but it is not working, any hints if I am doing something wrong:

mydict= {"(0.0, 0.1]":"<=10%","(0.1, 0.2]":">10% and <20%","(0.2, 0.3]":">20% and <30%", "(0.3, 0.4]":">30% and <40%", "(0.4, 0.5]":">40% and <50%", "(0.5, 0.6]":">50% and <60%", "(0.6, 0.7]":">60% and <70%", "(0.7, 0.8]":">70% and <80%", "(0.8, 0.9]":">80% and <90%", "(0.9, 1.0]":">90% and <100%", "(1.0, 2.0]":">100%"}
t_df["Ranges"].replace(mydict,inplace=True)

Thanks!

Upvotes: 1

Views: 153

Answers (2)

Sreeram TP
Sreeram TP

Reputation: 11907

By using map function this can be achieved easily and in a straight forward manner as shown below..

mydict= {"(0.0, 0.1]":"<=10%","(0.1, 0.2]":">10% and <20%","(0.2, 0.3]":">20% and <30%", "(0.3, 0.4]":">30% and <40%", "(0.4, 0.5]":">40% and <50%", "(0.5, 0.6]":">50% and <60%", "(0.6, 0.7]":">60% and <70%", "(0.7, 0.8]":">70% and <80%", "(0.8, 0.9]":">80% and <90%", "(0.9, 1.0]":">90% and <100%", "(1.0, 2.0]":">100%"}

t_df["Ranges"] = t_df["Ranges"].map(lambda x : mydict[str(x)])

Hope this helps..!!

Upvotes: 2

jezrael
jezrael

Reputation: 862481

I think here is best use parameter labels in time of create Ranges column in cut:

labels = ['<=10%','>10% and <20%', ...]
#change by your bins
bins = [0,0.1,0.2...]
t_df['Ranges'] = pd.cut(t_df['col'], bins=bins, labels=labels)

If not possible, cast to string should help as suggest @Dark in comments, for better performance use map:

t_df["Ranges"] = t_df["Ranges"].astype(str).map(mydict)

Upvotes: 2

Related Questions