Converting data in the lists to separated rows and columns in a new matrix

I would like to convert data lists to separated rows and columns in a new matrix. I will appreciate it if you have any advice or suggestions. I will give an example and what I did so far. The matrix at the beginning was like this;

Animals Names
1 Cat
2 Snake
3 Bird
1 Dog
2 Crocodile
3 Penguin

I wanted to group “names” in regard to their numbers in “animals” column

My codes are below;

from collections import defaultdict
d = defaultdict(list)

for key, val in df2:
    d[key].append(val)

Then I converted to an array of objects with the code;

df3 = np.array(list(dict.items(d)), dtype="object")

After applying those codes, it collected all the animals in the same group. For example;

1 — [Cat, Dog]

2 — [Snake, Crocodile]

3 — [Bird, Penguin]

However, what I actually would like to do is that, taking the whole data to a new matrix with an array of float64;

1 2 3
Cat Snake Bird
Dog Crocodile Penguin

Kind regards.

Answer

Try his:

df1 = pd.DataFrame( {
    'Animals': [1,2,3,1,2,3],
    'Names'  : ['Cat', 'Snake', 'Bird', 'Dog', 'Crocodile', 'Crocodile']
})

print(df1)

# df1.groupby('Animals')['Names'].apply(list).to_dict()
# {1: ['Cat', 'Dog'], 2: ['Snake', 'Crocodile'], 3: ['Bird', 'Crocodile']}

df2 = pd.DataFrame(df1.groupby('Animals')['Names'].apply(list).to_dict())

print(df2)

Output:

   Animals      Names
0        1        Cat
1        2      Snake
2        3       Bird
3        1        Dog
4        2  Crocodile
5        3  Crocodile


     1          2          3
0  Cat      Snake       Bird
1  Dog  Crocodile  Crocodile