学习内容
- 数据合并
- 数据聚合运算
学习笔记
1、stack函数是什么?
函数原型:np.stack(array,axis,out=None)
2、数据合并的方法
(1)使用concat方法
list_up = [text_left_up,text_right_up]
result_up = pd.concat(list_up,axis=1)
result_up.head()
(2)使用DataFrame自带的方法join和append方法
resul_up = text_left_up.join(text_right_up)
result_down = text_left_down.join(text_right_down)
result = result_up.append(result_down)
result.head()
(3)使用Panads的merge方法和DataFrame的append方法
result_up = pd.merge(text_left_up,text_right_up,left_index=True,right_index=True)
result_down = pd.merge(text_left_down,text_right_down,left_index=True,right_index=True)
result = resul_up.append(result_down)
result.head()
基础知识
一、pandas中groupby函数用法
(1)根据DataFrame本身的某一列或多列内容进行分组聚合
(a)若按某一列聚合,则新DataFrame将根据某一列的内容分为不同的维度进行拆解,同时将同一维度的再进行聚合
(b)若按某多列聚合,则新DataFrame将是多列之间维度的笛卡尔积,即:新DataFrame具有一个层次化索引(由唯一的键对组成),例如:“key1”列,有a和b两个维度,而“key2”有one和two两个维度,则按“key1”列和“key2”聚合之后,新DataFrame将有四个group;
(2)groupby(),根据分组键的不同,有以下4种聚合方法:
分组键为Series
(a)使用原df的子列作为Series
df.groupby([ df[‘key1’], df[‘key2’] ]).mean()
(b)使用自定义的Series
mapping={
‘a’:‘red’,‘b’:‘red’,‘c’:‘blue’,‘d’:‘blue’,‘e’:‘red’,‘f’:‘orange’}
map_series=pd.Series(mapping)
people.groupby(map_series,axis=1).count()
分组键为列名
df.groupby([ ‘key1’,‘key2’ ]).mean()
分组键为数组
states=np.array([‘Ohio’, ‘California’, ‘California’, ‘Ohio’, ‘Ohio’])
years=np.array([2004,2005,2006,2005,2006]) #自定义数组
df[‘data1’].groupby( [ states,years ] ).mean()
分组键为字典
mapping={
‘a’:‘red’,‘b’:‘red’,‘c’:‘blue’,‘d’:‘blue’,‘e’:‘red’,‘f’:‘orange’} #自定义字典
by_column=people.groupby(mapping,axis=1).sum() #指定axis=1,表示对列数据进行聚合分组
分组键为函数
例如:传入len函数(可以求取一个字符串长度数组),实现根据字符串的长度进行分组
people.groupby(len).sum() #将字符串长度相同的行进行求和
分组键为函数和数组、列表、字典、Series的组合
引入列表list[ ] 将函数跟数组、列表、字典、Series混合使用作为分组键进行聚合,因为任何东西最终都会被转换为数组
key_list=[‘one’,‘one’,‘one’,‘two’,‘two’] #自定义列表,默认列表顺序和df的列顺序一致
people.groupby([ len,key_list ]).min()
分组键为具有多重列索引df 的列索引层次
hier_df.groupby(level=‘cty’,axis=1).count() #利用参数level,指明聚合的层级
(3)常用配合函数/方法
1、打印出按某一指定列进行聚合的DataFrame:
for i in df.groupby('key1'):
print(i)
2、groupby()语法格式
DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True,group_keys=True, squeeze=False, observed=False, **kwargs)
groupby()典型范例
范例一:根据DataFrame本身的某一列或多列内容进行分组聚合
#创建原始数据集
import pandas as pd
import numpy as np
df=pd.DataFrame({
'key1':['a','a','b','b','a'],
'key2':['one','two','one','two','one'],
'data1':np.random.randn(5),
'data2':np.random.randn