我想将数据列表转换为新矩阵中分隔的行和列。如果你有任何意见或建议,我将不胜感激。我将给出一个例子,以及我目前所做的。一开始的矩阵是这样的;
<表类>
动物名称 tbody><<tr>1 猫 2蛇 3 鸟 1狗 2鳄鱼 3 企鹅 表类>
Try this:
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