将列表中的数据转换为新矩阵中的分隔行和列

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

我想将数据列表转换为新矩阵中的分隔行和列。如果您有任何意见或建议,我将不胜感激。我将举一个例子以及我到目前为止所做的。 一开始的矩阵是这样的;

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

我想根据“动物”列中的数量对“名称”进行分组

我的代码如下;

from collections import defaultdict
d = defaultdict(list)

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

然后我用代码转换为对象数组;

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

应用这些代码后,它收集了同一组中的所有动物。例如;

1 -- [猫,狗]

2 -- [蛇,鳄鱼]

3 -- [鸟、企鹅]

但是,我真正想做的是,将整个数据放入一个包含 float64 数组的新矩阵;

1 2 3
Cat Snake Bird
Dog Crocodile Penguin

亲切的问候。

试试他的:

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)

输出:

   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