如何对一列进行分组而不对 pandas 中的其他列进行分组?

How to grouby one column and do nothing to other columns in pandas?

我有一个这样的数据框:

  a  b  c  d 
0 1  1  1  1
1 1  2  2  2
2 1  3  3  3
3 1  4  4  4
4 2  1  1  1
5 2  2  2  2
6 2  3  3  3

如何分组 'a',不对 b c d 列进行任何操作,并将其拆分为多个数据帧?像这样: 第一个 groupby 列 'a':

  a  b  c  d 
0 1  1  1  1
1    2  2  2
2    3  3  3
3    4  4  4
4 2  1  1  1
5    2  2  2
6    3  3  3

然后根据'a'中的数字分成不同的数据帧:

dataframe 1:

      a  b  c  d 
    0 1  1  1  1
    1    2  2  2
    2    3  3  3
    3    4  4  4
dataframe 2:
      a  b  c  d 
    0 2  1  1  1
    1    2  2  2
    2    3  3  3
:
:
:
dataframe n:
      a  b  c  d 
    0 n  1  1  1
    1    2  2  2
    2    3  3  3 

遍历 df.groupby returns.

的每个组
for _, g in df.groupby('a'):
     print(g, '\n')

   a  b  c  d
0  1  1  1  1
1  1  2  2  2
2  1  3  3  3
3  1  4  4  4 

   a  b  c  d
4  2  1  1  1
5  2  2  2  2
6  2  3  3  3 

如果你想要数据框的字典,我建议:

df_dict = {idx : g for idx, g in df.groupby('a')}

这里,idx 是唯一的 a 值。


一些巧妙的技巧 :

df_dict = dict(list(df.groupby('a')))  # for a dictionary

而且,

idxs, dfs = zip(*df.groupby('a'))       # separate lists
idxs
(1, 2)

dfs
(   a  b  c  d
 0  1  1  1  1
 1  1  2  2  2
 2  1  3  3  3
 3  1  4  4  4,    a  b  c  d
 4  2  1  1  1
 5  2  2  2  2
 6  2  3  3  3)

这是使用np.split

的方法
idx=df.a.diff().fillna(0).nonzero()[0]
dfs = np.split(df, idx, axis=0)

dfs
Out[210]: 
[   a  b  c  d
 0  1  1  1  1
 1  1  2  2  2
 2  1  3  3  3
 3  1  4  4  4,    a  b  c  d
 4  2  1  1  1
 5  2  2  2  2
 6  2  3  3  3]
dfs[0]
Out[211]: 
   a  b  c  d
0  1  1  1  1
1  1  2  2  2
2  1  3  3  3
3  1  4  4  4