【问题标题】:groupby in pandas and exclude grouper column from output DataFramepandas 中的 groupby 并从输出 DataFrame 中排除 grouper 列
【发布时间】:2021-01-02 15:34:05
【问题描述】:

我正在尝试对 pandas df 进行分组,以便它将键保留为索引,但它不包含每个组中的键。

这是我的意思的一个例子。

  1. 原始数据帧

    ungrouped_df = pd.DataFrame({'col1':['A','A','B','C','C','C'], 'col2':[8,5,1,4,1,2], 'col3':[7,4,2,1,2,1],'col4':[1,8,0,2,0,0]})

出来:

| index | col1 | col2 | col3 | col4 |
|-------|------|------|------|------|
| 1     |    A |    8 |    7 |    1 |
| 2     |    A |    5 |    4 |    8 |
| 3     |    B |    1 |    2 |    0 |
| 4     |    C |    4 |    1 |    2 |
| 5     |    C |    1 |    2 |    0 |
| 6     |    C |    2 |    1 |    0 |
  1. 现在,我想从分组数据框创建一个 numpy 数组

    grouped_df = ungrouped_df.groupby(by='col1', group_keys=False).apply(np.asarray)

这就是我得到的

| index | col1                                      | 
|-------|-------------------------------------------|
| A     | [[A, 8, 7, 1],[A, 5, 4, 8],[A, 8, 7, 1]]  |
| B     | [[B, 1, 2, 0]]                            |
| C     | [[C, 4, 1, 2], [C, 1, 2, 0], [C, 2, 1, 0]]|
  1. 这正是我想要得到的

出来:

| index | col1                             | 
|-------|----------------------------------|
| A     | [[8, 7, 1],[5, 4, 8],[8, 7, 1]]  |
| B     | [[1, 2, 0]]                      |
| C     | [[4, 1, 2], [1, 2, 0], [2, 1, 0]]|

我可以在这里使用一些建议,因为我有点迷茫。我认为“group_keys = False”可以解决问题,但事实并非如此。非常感谢任何帮助。

谢谢

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    我通常不建议将列表存储在列中,但解决此问题的最明显方法是确保不对不需要的列进行分组。

    您可以指定任一方式

    1. 将“col1”设置为分组前的索引,或者
    2. 在分组前删除“col1”,或者
    3. 选择要分组的列

    df.set_index('col1').groupby(level=0).apply(np.array)
    
    col1
    A               [[8, 7, 1], [5, 4, 8]]
    B                          [[1, 2, 0]]
    C    [[4, 1, 2], [1, 2, 0], [2, 1, 0]]
    

    或,

    df.drop('col1', 1).groupby(df['col1']).apply(np.array)
    
    col1
    A               [[8, 7, 1], [5, 4, 8]]
    B                          [[1, 2, 0]]
    C    [[4, 1, 2], [1, 2, 0], [2, 1, 0]]
    

    或,

    (df.groupby('col1')[df.columns.difference(['col1'])]
       .apply(lambda x: x.values.tolist()))
    
    col1
    A               [[8, 7, 1], [5, 4, 8]]
    B                          [[1, 2, 0]]
    C    [[4, 1, 2], [1, 2, 0], [2, 1, 0]]
    dtype: object
    

    【讨论】:

    • 嗨,第一个和第二个选项非常适合我的情况。就这么简单!非常感谢:)
    【解决方案2】:

    让我们试试pd.Series.groupby

    df = df.drop('col1',1).agg(list,1).groupby(df.col1).agg(list).reset_index(name='out')
    

    ...

    df
      col1                                out
    0    A             [[8, 7, 1], [5, 4, 8]]
    1    B                        [[1, 2, 0]]
    2    C  [[4, 1, 2], [1, 2, 0], [2, 1, 0]]
    

    【讨论】:

    • 嗯,输出似乎不对,结果中应该只存在整数。你能看看吗? :-)
    猜你喜欢
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 2017-08-30
    • 2013-07-14
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    相关资源
    最近更新 更多