dataframe 分组groupby显示方法 (单纯显示,无其它操作如sum,mean)

#总结这是纯显示分组的最佳方法
d2 = df.groupby('id').apply(lambda x:x[:]).drop(axis=1,columns='id',inplace=False)
d2 # 最佳方法; just modify df itself,inplace=True

纯显示分组是这样最好,但建议不要.drop(axis=1,columns=‘id’,inplace=False) ,因为做针对性查询的时候会有麻烦。详情可搜索该行代码及看其前后: 
d3 = df.groupby(‘id’).apply(lambda x:x[:])

此外别误以为groupby会自动对每组的数字求和,求和还得加.sum([])。df.groupby(‘id’).first() 真的只会取每组的第一行记录,所以要小心使用,避免漏掉其余行的数据。

import pandas as pd
d = {'id':[1,1,2,3,3,4,3,4,1,5],'product':['p2','p1','p3','p2','p1','p3','p4','p5','p6','p5']}
df = pd.DataFrame.from_dict(d).reset_index(drop=True) # .reset_index(drop=True) 只能对index重置,无法删除
df

out:

	id 	product
0 	1 	p2
1 	1 	p1
2 	2 	p3
3 	3 	p2
4 	3 	p1
5 	4 	p3
6 	3 	p4
7 	4 	p5
8 	1 	p6
9 	5 	p5

#############

# 想以dataframe形式来展示,这不够好看
for i,j in df.groupby('id'):
    print(i,j)

out:

1    id product
0   1      p2
1   1      p1
8   1      p6
2    id product
2   2      p3
3    id product
3   3      p2
4   3      p1
6   3      p4
4    id product
5   4      p3
7   4      p5
5    id product
9   5      p5
d2 = df.groupby('id').apply(lambda x:x[:]).drop(axis=1,columns='id',inplace=False)
d2 # 最佳方法
 		product
id 		
1 	0 	p2
	1 	p1
	8 	p6
2 	2 	p3
3 	3 	p2
	4 	p1
	6 	p4
4 	5 	p3
	7 	p5
5 	9 	p5
d2.index

out:

MultiIndex([(1, 0),
            (1, 1),
            (1, 8),
            (2, 2),
            (3, 3),
            (3, 4),
            (3, 6),
            (4, 5),
            (4, 7),
            (5, 9)],
           names=['id', None])
d2[d2.index=='3'] # can't find anything
 		product
id 		
d3 =  df.groupby('id').apply(lambda x:x[:])
d3 # d3[d3.index=='3'] still can't find anythings,but I can find it in cloumns='id'
 		id 	product
id 			
1 	0 	1 	p2
	1 	1 	p1
	8 	1 	p6
2 	2 	2 	p3
3 	3 	3 	p2
	4 	3 	p1
	6 	3 	p4
4 	5 	4 	p3
	7 	4 	p5
5 	9 	5 	p5
d3[d3['id']==3] # type(id) is int, but id as index,you have to find it in str '3';
 		id 	product
id 			
3 	3 	3 	p2
	4 	3 	p1
	6 	3 	p4
# 看可否去掉index来优化显示
df2.to_excel('aa.xlsx',engine='openpyxl',index=False) 

excel:
excel

from IPython.display import HTML
HTML(df2.to_html(index=False)) # 发现只要把index去掉都会导致每组只显示一个元素,此外index可反映对应元素的下标,所以去掉它的意义不大。
id 	product
1 	p2
2 	p3
3 	p2
4 	p3
5 	p5
df3 = df.groupby('id').head(2) # 当.head(n)的 n=1,展示的数组和df.groupby('id').first()一样,但格式稍有区别,
# 它只是取每种类型的前n个,而非分组后再取前n个(不作分组归类,别以为goupby就一定归类)
# 我为该程序单独用d = {'id':[1,1,2,3,3,4,3,4,1,5,2],'product':['p2','p1','p3','p2','p1','p3','p4','p5','p6','p5','p8']}
df3
 	id 	product
0 	1 	p2
1 	1 	p1
2 	2 	p3
3 	3 	p2
4 	3 	p1
5 	4 	p3
7 	4 	p5
9 	5 	p5
10 	2 	p8

#############

d_first = df.groupby('id').first() # 取出各分组第一个元素作展示
d_first

out:

 	product
id 	
1 	p2
2 	p3
3 	p2
4 	p3
5 	p5
df3 == df_first # 拓展一下,这2表看似相同,但表结构有差异(df_first被看作id为索引的表,
# 而df3.index会报错 'HTML' object has no attribute 'index'),所以不等。

out:

 	product
id 	
1 	False
2 	False
3 	False
4 	False
5 	False
d_last = df.groupby('id').last() #  取出各分组倒数第一个元素作展示
d_last

out:

 	product
id 	
1 	p6
2 	p3
3 	p4
4 	p5
5 	p5
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用Pandas库中的groupby函数对DataFrame进行分组聚合操作。对于问题中提到的无法输出结果的情况,可能是由于数据类型的问题导致的。可以使用apply函数将需要聚合的列转换为浮点型后再进行mean的计算。下面是一个示例代码: ```python import pandas as pd import numpy as np # 创建一个示例DataFrame df = pd.DataFrame(np.random.random([5, 5]), columns=['a', 'b', 'c', 'd', 'e']) df["index_"] = [1, 1, 2, 2, 3] # 将需要聚合的列转换为浮点型 df[['a', 'b', 'c', 'd', 'e']] = df[['a', 'b', 'c', 'd', 'e']].apply(np.float64) # 使用groupby和mean进行聚合操作 result = df.groupby('index_').mean() # 输出结果 print(result) ``` 上述代码首先创建了一个示例的DataFrame,并给其中一列赋予了分组的标识。然后使用apply函数将需要聚合的列转换为浮点型。最后使用groupby和mean函数对DataFrame进行分组聚合操作,并将结果输出。请注意,这只是一个示例,实际的操作可能会有所不同。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [python.DataFame,groupby,可以sum(),但是mean()不返回值](https://blog.csdn.net/jackson_shy/article/details/123792345)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值