python-3.x - 根据变量的当前出现对行进行分组
问题描述
我正在尝试根据变量的出现对数据框进行分组。例如采取这个数据框
| 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
解决方案
我建议创建 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
推荐阅读
- java - 从 nodejs 加密和 Java 加密产生相同的结果
- javascript - 使用 XmlHttpRequest 发送文件并在 express/multer 中接收
- tensorflow - tf.signal.rfft2d 输出形状?
- google-sheets - 将公式(不是值)从主工作表推送到子工作表
- python - Google Kick Start Round A for Python 中的运行时错误
- python - Django背景图像不起作用如何修复?
- excel - 带有变量和数组的 Excel VBA RC 表示法
- size - 将 binutils `size` 输出从“sysv”格式(`size --format=sysv my_executable`)转换为“berkeley”格式(`size --format=berkeley my_executable`)
- python - 如何在 Django CreateView 中创建对象后添加指令?
- pandas - 为 Pandas 中的组计算特定列的最大值