Monthly Archives: 十月 2023

Hello World

pandas之pivot_table的使用

pivot_table是将多行数据转成多列的一个函数,作用类似exce的透视表,这里咱们先看一下它的实际处理效果:

再看代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
#构建测试数据
df = pd.DataFrame({
	'品类': ['苹果', '橘子', '香蕉', '橘子', '香蕉', '橘子'],
	'日期': ['2023-10-21', '2023-10-21', '2023-10-21', '2023-10-22', '2023-10-23','2023-10-23'],
	'销量': [13, 24, 25, 27, 19, 21]
	},
	columns=['品类', '日期', '销量']
)
print(df)
#日期列转行 index 行索引,columns 要转为列名的行,values 要转为列值的行
df2 = pd.pivot_table(df, index=['品类'], columns=['日期'], values=['销量'])
df2.fillna(0, inplace=True)
print(df2)

———-
over,转载请注明出处:http://www.jiangkl.com/2023/10/pivot_table