Reputation: 3164
I have a dataframe which looks something like this:
df = pd.DataFrame([['7690d79f','Pos'],['7690d79f','Neg'],['7690d79f','Pos'],['7690d79f','Neu'],\
['6690d79f','Pos'],['6690d79f','Neg'],['6690d79f','Pos'],['6690d79f','Neu']]\
,columns=['id', 'vote'])
which is:
id vote
0 7690d79f Pos
1 7690d79f Neg
2 7690d79f Pos
3 7690d79f Neu
4 6690d79f Pos
5 6690d79f Neg
6 6690d79f Pos
7 6690d79f Neu
I want to pivot rows to columns such that, I get a resultDF as
id vote_1 vote_2 vote_3 vote_4
7690d79f Pos Neg Pos Neu
6690d79f Pos Neg Pos Neu
If it helps, there is no more than 4 votes per ids.
Though this is similar to
But unfortunately, none of them works for me.
Upvotes: 1
Views: 227
Reputation: 153460
Let's try this:
df1 = df.groupby('id')['vote'].apply(lambda x: pd.DataFrame(x.tolist())).unstack()
df1.columns = df1.columns.droplevel().values + 1
df1.add_prefix('vote_').reset_index()
Output:
id vote_1 vote_2 vote_3 vote_4
0 6690d79f Pos Neg Pos Neu
1 7690d79f Pos Neg Pos Neu
Upvotes: 2