Python pandas中的groupby和从输出数据帧中排除grouper列
我正在尝试按一个索引进行分组,这样它就可以将键保留为索引,但不会将键包含在每个组中 这是我的意思的一个例子Python pandas中的groupby和从输出数据帧中排除grouper列,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我正在尝试按一个索引进行分组,这样它就可以将键保留为索引,但不会将键包含在每个组中 这是我的意思的一个例子 原始数据帧 ungroup_df=pd.DataFrame({'col1':[A','A','B','C','C','C','C'],'col2':[8,5,1,4,1,2],'col3':[7,4,2,1,2,1],'col4':[1,8,0,2,0,0]}) 输出: 现在,我想从分组的数据帧创建一个numpy数组 grouped\u df=ungroup\u df.groupby(b
ungroup_df=pd.DataFrame({'col1':[A','A','B','C','C','C','C'],'col2':[8,5,1,4,1,2],'col3':[7,4,2,1,2,1],'col4':[1,8,0,2,0,0]})
grouped\u df=ungroup\u df.groupby(by='col1',group\u keys=False).应用(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]]|
谢谢我通常不建议将列表存储在列中,但最明显的解决方法是确保不需要的列不会被分组 您可以通过以下两种方式指定
或者 或者
让我们试试
pd.Series.groupby
df = df.drop('col1',1).agg(list,1).groupby(df.col1).agg(list).reset_index(name='out')
嗯,输出似乎不正确,结果中应该只有整数。你能看一下吗?:-)@cs95太好了~修正了~谢谢你,曼希,第一个和第二个选项对我来说都很好。就这么简单!非常感谢:)
| 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]]|
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
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]]