Pandas update column with array

Viewed 1091

So, I'm learning pandas and I have this problem.

Suppose I have a Dataframe like this:

A B C
1 x NaN
2 y NaN
3 x NaN
4 x NaN
5 y NaN

I'm trying to create this:

A B C
1 x [1,3,4]
2 y [2,5]
3 x [1,3,4]
4 x [1,3,4]
5 y [2,5]

Based on B similarities.

I did this:

teste = df.groupby(['B'])
for name,group in teste:
    df.loc[df['B'] == name[0],'C'] = group['A'].tolist()

And I got this. Like the C column is based on A column.

A B C
1 x 1
2 y 2
3 x 3
4 x 4
5 y 5

Can anybody explain to me why this is happening and a solution to do this the way I want? Thanks :)

4 Answers
Related