1

I have a dataframe that looks something like this:

data = [['A', 1, 100], ['A', 3, 100], ['A', 2, 100], ['A', 3, 100], ['A', 5, 100]]
df =  pd.DataFrame(data, columns = ['?', 'Rating', 'Amount'])
    ?   Rating  Amount
0   A   1       100
1   A   3       100
2   A   2       100
3   A   3       100
4   A   5       100

and I need to create new columns based on the Rating value substituting in the amount - looks something like this:

    ?   Rating  Amount  1   2   3   5
0   A   1       100     100 0   0   0
1   A   3       100     0   0   100 0
2   A   2       100     0   100 0   0
3   A   3       100     0   0   100 0
4   A   5       100     0   0   0   100

Right now I have this:

ratingnames = np.unique(list(df['Rating']))
ratingnames.sort()

d = pd.DataFrame(0, index=np.arange(len(df['Rating'])), columns=ratingnames)

for i in range(len(df['Rating'])):
    ratingvalue = df.loc[i, 'Rating']
    d.loc[i, ratingvalue] = df.loc[i, 'Amount']

df = pd.concat([df, d], axis = 1)

but I feel like it could be improved upon. Any suggestions? Thanks!

2 Answers 2

2

IIUC, use get_dummies and multiply with df['Amount'], then concat on axis=1:

output = pd.concat((df,pd.get_dummies(df['Rating']).mul(df['Amount'],axis=0)),axis=1)

   ?  Rating  Amount    1    2    3    5
0  A       1     100  100    0    0    0
1  A       3     100    0    0  100    0
2  A       2     100    0  100    0    0
3  A       3     100    0    0  100    0
4  A       5     100    0    0    0  100

Timings: enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

@ecaines You should not use apply when not required in pandas especially axis=1 is very slow. Added some timing test to demonsrate what I meant
interesting, thanks for adding that in. very helpful
@ecaines no problem ..happy coding :)
1

This will do the trick:

df=pd.concat([df, df.apply(lambda x: pd.Series({x["Rating"]: x["Amount"]}), axis=1).fillna(0).astype("int")], axis=1)

Output:

   ?  Rating  Amount    1    2    3    5
0  A       1     100  100    0    0    0
1  A       3     100    0    0  100    0
2  A       2     100    0  100    0    0
3  A       3     100    0    0  100    0
4  A       5     100    0    0    0  100

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.