数据分析-数据重构

本文详细介绍了在数据分析中如何进行数据重构,包括数据合并和数据聚合运算。重点讲解了pandas中groupby函数的使用,包括根据DataFrame的列进行分组、不同类型的分组键如Series、列名、数组、字典、函数以及它们的组合,以及配合使用的常用函数。通过多个实例展示了如何进行分组聚合操作。
摘要由CSDN通过智能技术生成

学习内容

  1. 数据合并
  2. 数据聚合运算

学习笔记

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值