pandas使用教程:pandas计数count和索引设置set_index、reset_index

计数函数count

  • 导入excel数据表
import pandas as pd

df = pd.read_excel('team.xlsx')
df
	name	team	Q1	Q2	Q3	Q4
0	Liver	E	89	21	24	64
1	Arry	C	36	37	37	57
2	Ack	A	57	60	18	84
3	Eorge	C	93	96	71	78
4	Oah	D	65	49	61	86
...	...	...	...	...	...	...
95	Gabriel	C	48	59	87	74
96	Austin7	C	21	31	30	43
97	Lincoln4	C	98	93	1	20
98	Eli	E	11	74	58	91
99	Ben	E	21	43	41	74
100 rows × 6 columns
  • count计数(默认按行计数)
df.count()

name    100
team    100
Q1      100
Q2      100
Q3      100
Q4      100
dtype: int64
  • count按列计数
df.count(axis='columns')

0     6
1     6
2     6
3     6
4     6
     ..
95    6
96    6
97    6
98    6
99    6
Length: 100, dtype: int64
  • count多级索引
    将team设为行索引,
df.set_index(["team", "name"]).count(level="team")

	Q1	Q2	Q3	Q4
team				
A	17	17	17	17
B	22	22	22	22
C	22	22	22	22
D	19	19	19	19
E	20	20	20	20

效果等同于对team列先分组再计数

df.groupby(by='team').count()

	name	Q1	Q2	Q3	Q4
team					
A	17	17	17	17	17
B	22	22	22	22	22
C	22	22	22	22	22
D	19	19	19	19	19
E	20	20	20	20	20

计数函数value_counts

  • 统计team列个数
df['team'].value_counts()

C    22
B    22
E    20
D    19
A    17
Name: team, dtype: int64
  • 统计team列个数,并按value值升序排序
df['team'].value_counts(ascending=True)

A    17
D    19
E    20
B    22
C    22
Name: team, dtype: int64
  • 统计team列个数,按value值升序排序并计算百分比
df['team'].value_counts(ascending=True,normalize=True)

A    0.17
D    0.19
E    0.20
B    0.22
C    0.22
Name: team, dtype: float64

索引设置set_index

将指定一列设置为索引

df.set_index('name')

team	Q1	Q2	Q3	Q4
name					
Liver	E	89	21	24	64
Arry	C	36	37	37	57
Ack	A	57	60	18	84
Eorge	C	93	96	71	78
Oah	D	65	49	61	86
...	...	...	...	...	...
Gabriel	C	48	59	87	74
Austin7	C	21	31	30	43
Lincoln4	C	98	93	1	20
Eli	E	11	74	58	91
Ben	E	21	43	41	74
100 rows × 5 columns

如果添加参数drop = False,表示不删除原来的name一列。

inplace=True时,表示在原来的dataframe上修改,inplace=False时,表示不更改源dataframe。

索引重设reset_index

对于之前set_index之后的dataframe进行处理。

更改原索引为新的一列,重新设置数字索引。drop = True时,原来的索引列name被删除。drop = False时,原来的索引列name继续保留到dataframe中。

df.reset_index(drop=True)  

	name	team	Q1	Q2	Q3	Q4
0	Liver	E	89	21	24	64
1	Arry	C	36	37	37	57
2	Ack	A	57	60	18	84
3	Eorge	C	93	96	71	78
4	Oah	D	65	49	61	86
...	...	...	...	...	...	...
95	Gabriel	C	48	59	87	74
96	Austin7	C	21	31	30	43
97	Lincoln4	C	98	93	1	20
98	Eli	E	11	74	58	91
99	Ben	E	21	43	41	74
100 rows × 6 columns

猜你喜欢

转载自blog.csdn.net/weixin_46530492/article/details/131822682
今日推荐