【发布时间】:2023-02-02 15:59:08
【问题描述】:
我有一个这样的数据框
col1 col2 col3 col4 action_id
0 1 2 2 0 a, apple
1 1 2 3 5 b, apple
2 0.2 0.3 8 1 c, apple
3 0.2 0.02 1 2 a, apple
4 11 11 22 11 b, apple
我想将此数据框转换为字典,其中 action_id 作为我的键,其他人作为我的值。
我希望以这种方式输出:
{('a', 'apple'): array([[1, 2, 2, 0]]),
('b', 'apple'): array([[1, 2, 3, 5]]),
('c', 'apple'): array([[0.2, 0.3, 8, 1]]),
('a', 'apple'): array([[0.2, 0.02, 1, 2]]),
('b', 'apple'): array([[11, 11, 22, 11]])}
我试过这个方法
data2d = var.set_index('action_id').T.to_dict('list') 考虑将 var 作为我的数据框。
但是这种方法是用重复键覆盖 dict 中的值,并且只返回重复键中的最后一个值。有什么办法可以获得具有不同值的重复键吗?
{('c', 'apple'): array([[0.2, 0.3, 8, 1]]),
('a', 'apple'): array([[0.2, 0.02, 1, 2]]),
('b', 'apple'): array([[11, 11, 22, 11]])}
【问题讨论】:
-
这是不可能的, 字典不能有重复的键。你必须找到另一个输出。