我需要做一个模糊groupby
,其中一个记录可以在一个或多个组中。在
我有一个这样的DataFrame
:
test = pd.DataFrame({'score1' : pandas.Series(['a', 'b', 'c', 'd', 'e']), 'score2' : pd.Series(['b', 'a', 'k', 'n', 'c'])})
输出:
^{pr2}$组键应该是score1
和score2
之间的唯一值的并集。记录0
应该在a
和{1
应该在组b
和{c
和{
我试过在两个列上进行groupby,如下所示:
In [192]: score_groups = pd.groupby(['score1', 'score2'])
但是,我得到的组键是元组-(1,2),(2,1),(3,8)等,而不是记录可以在多个组中的唯一组键。输出如下:
In [192]: score_groups.groups
Out[192]: {('a', 'b'): [0],
('b', 'a'): [1],
('c', 'k'): [2],
('d', 'n'): [3],
('e', 'c'): [4]}
另外,我需要保留索引,因为我将在以后的另一个操作中使用它们。 请帮忙!在
将两个
columns
组合成一个column
,例如pd.concat()
:然后在}:
^{pr2}$'grp'
上.groupby()
并在list
中收集{或者,如果您喜欢
dict
:或者,在一个步骤中达到相同效果,跳过重命名列:
重新组织数据以便于操作(对同一数据使用多个值列总是会让您头疼)。在
现在,您的值只有一列,很容易按分数分组或按姓名选择列:
^{pr2}$在Stefan的帮助下,我解决了这个问题。在
注意重复的索引。索引被保存了,这正是我想要的。现在,让我们开始谈业务-按操作分组。在
^{pr2}$我很困惑pandas如何使用正确的索引检索行,即使它们是重复的。据我所知,groupby操作使用反向索引数据结构来存储对行的引用(索引)。任何见解都将不胜感激。任何回答此问题的人都将接受他们的答案:)
相关问题 更多 >
编程相关推荐