groupby多个值列

2024-09-28 21:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要做一个模糊groupby,其中一个记录可以在一个或多个组中。在

我有一个这样的DataFrame

test = pd.DataFrame({'score1' : pandas.Series(['a', 'b', 'c', 'd', 'e']), 'score2' : pd.Series(['b', 'a', 'k', 'n', 'c'])})

输出:

^{pr2}$

我希望有这样的团体: enter image description here

组键应该是score1score2之间的唯一值的并集。记录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]}

另外,我需要保留索引,因为我将在以后的另一个操作中使用它们。 请帮忙!在


Tags: intestdataframepandas记录seriespdgroups
3条回答

将两个columns组合成一个column,例如pd.concat()

s = pd.concat([test['score1'], test['score2'].rename(columns={'score2': 'score1'})]).reset_index()
s.columns = ['val', 'grp']

   val grp
0    0   a
1    1   b
2    2   c
3    3   d
4    4   e
5    0   b
6    1   a
7    2   k
8    3   n
9    4   c

然后在'grp'.groupby()并在list中收集{}:

^{pr2}$

或者,如果您喜欢dict

s.to_dict()

{'e': [4], 'd': [3], 'n': [3], 'k': [2], 'a': [0, 1], 'c': [2, 4], 'b': [1, 0]}

或者,在一个步骤中达到相同效果,跳过重命名列:

test.unstack().reset_index(-1).groupby(0).apply(lambda x: x.level_1.tolist())

a    [0, 1]
b    [1, 0]
c    [2, 4]
d       [3]
e       [4]
k       [2]
n       [3]

重新组织数据以便于操作(对同一数据使用多个值列总是会让您头疼)。在

import pandas as pd

test = pd.DataFrame({'score1' : pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e']), 'score2' : pd.Series([2, 1, 8, 9, 3], index=['a', 'b', 'c', 'd', 'e'])})

test['name'] = test.index
result = pd.melt(test, id_vars=['name'], value_vars=['score1', 'score2'])

  name variable  value
0    a   score1      1
1    b   score1      2
2    c   score1      3
3    d   score1      4
4    e   score1      5
5    a   score2      2
6    b   score2      1
7    c   score2      8
8    d   score2      9
9    e   score2      3

现在,您的值只有一列,很容易按分数分组或按姓名选择列:

^{pr2}$

Stefan的帮助下,我解决了这个问题。在

In (283): frame1 = test[['score1']]
          frame2 = test[['score2']]
          frame2.rename(columns={'score2': 'score1'}, inplace=True)

          test = pandas.concat([frame1, frame2])

          test

Out[283]:   
   score1
0   a
1   b
2   c
3   d
4   e
0   b
1   a
2   k
3   n
4   c

注意重复的索引。索引被保存了,这正是我想要的。现在,让我们开始谈业务-按操作分组。在

^{pr2}$

我很困惑pandas如何使用正确的索引检索行,即使它们是重复的。据我所知,groupby操作使用反向索引数据结构来存储对行的引用(索引)。任何见解都将不胜感激。任何回答此问题的人都将接受他们的答案:)

相关问题 更多 >