首页 > 解决方案 > 根据变量的当前出现对行进行分组

问题描述

我正在尝试根据变量的出现对数据框进行分组。例如采取这个数据框

   | col_1 | col_2
---------------------
 0 | 1     | 1
 1 | 0     | 1
 2 | 0     | 1
 3 | 0     | -1
 4 | 0     | -1
 5 | 0     | -1
 6 | 0     | NaN
 7 | -1    | NaN
 8 | 0     | NaN
 9 | 0     | -1
 10| 0     | -1
 11| 0     | -1

我想根据 column_2 中当前出现的变量将变量分组到一个数据帧,并将下一个序列放入另一个数据帧,同样直到数据帧结束,同时也忽略 NaN。

所以最终的输出就像:ones_1 =

   | col_1 | col_2
---------------------
 0 | 1     | 1
 1 | 0     | 1
 2 | 0     | 1

mones_1 =

 3 | 0     | -1
 4 | 0     | -1
 5 | 0     | -1

mones_2 =

 9 | 0     | -1
 10| 0     | -1
 11| 0     | -1

标签: python-3.xpandaspandas-groupby

解决方案


我建议创建 DataFrames 字典:

#only non missing rows
mask = df['col_2'].notna()
#create unique groups
g = df['col_2'].ne(df['col_2'].shift()).cumsum()
#create counter of filtered g
g = g[mask].groupby(df['col_2']).transform(lambda x:pd.factorize(x)[0]) + 1
#map positive and negative values to strings and add counter values
g = df.loc[mask, 'col_2'].map({-1:'mones_',1:'ones_'}) + g.astype(str)
#generally groups
#g = 'val' + df.loc[mask, 'col_2'].astype(str) + ' no' + g.astype(str)
print (g)
0      ones_1
1      ones_1
2      ones_1
3     mones_1
4     mones_1
5     mones_1
9     mones_2
10    mones_2
11    mones_2
Name: col_2, dtype: object

#create dictionary of DataFrames
dfs = dict(tuple(df.groupby(g)))
print (dfs)
{'mones_1':    col_1  col_2
3      0   -1.0
4      0   -1.0
5      0   -1.0, 'mones_2':     col_1  col_2
9       0   -1.0
10      0   -1.0
11      0   -1.0, 'ones_1':    col_1  col_2
0      1    1.0
1      0    1.0
2      0    1.0}

#select by keys
print (dfs['ones_1'])
   col_1  col_2
0      1    1.0
1      0    1.0
2      0    1.0

推荐,但可以使用变量名按组创建 DataFrame:

for i, g in df.groupby(g):
    globals()[i] =  g

print (ones_1)
   col_1  col_2
0      1    1.0
1      0    1.0
2      0    1.0

推荐阅读