数据分析与可视化 实践基础练习五 (Pandas)
一、本节需要掌握的Pandas相关函数或属性
Pandas数据运算
Pandas常用的汇总与统计性方法
数据分组df.groupby( )
参数by:可以是函数,字典,Series; axis=0是按列,1是按行
数据聚合agg()、apply()、transform()
agg(): 可对分组后的数据进行一系列的操作包含求和求最值,均值等
apply(): 可自定义面向分组的聚合函数(Series对象是对每个元素处理,DataFrame对象是对一行或一列处理,groupby对象是对一个分组进行处理)
transfrom(): 不对数据进行聚合输出,而只是对每一行记录提供了相应的聚合结果(输出结果有冗余)
二、实训案例
1.行星数据集记录了2014年之前发现的行星的信息,数据中主要特征有:
planets.csv 数据集下载
2. 结合数据集完成以下操作。
(1)读取planets.csv文件;
(2)查看数据前5行;
(3)查看数据基本情况;
(4)按method特征对数据进行分组,并将新数据记为grouped;
(5)将数据按发现年份在2000年前和2000年后进行分组;
(6)求2000年前和2000年后的分组均值;
(7)查看不同方法发现的行星与地球距离的中位数;
(8)按发现行星的方法和发现的年代进行分组,并统计相应分组下发现的行星的总数;
(9)计算不同方法发现的行星在各特征上的极差;
(10)分别计算各种方法发现的行星的距离的均值和发现的数量之和。
三、题解
1 2 3 4 5 6 7 8
|
import pandas as pd df = pd.read_csv('planets.csv',sep = ',')
df.head()
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| <class 'pandas.core.frame.DataFrame'> RangeIndex: 1035 entries, 0 to 1034 Data columns (total 6 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 method 1035 non-null object 1 number 1035 non-null int64 2 orbital_period 992 non-null float64 3 mass 513 non-null float64 4 distance 808 non-null float64 5 year 1035 non-null int64 dtypes: float64(3), int64(2), object(1) memory usage: 48.6+ KB
|
1 2 3 4 5 6
|
grouped = df.groupby('method') grouped.head(3)
|
1 2 3 4 5 6 7 8
|
col_new = 'Before 2000' df.insert(6, col_new, df['year'] < 2000)
group = df.groupby('Before 2000') group.head()
|

1 2 3
|
df.groupby('method')['distance'].median()
|
1 2 3 4 5 6 7 8 9 10 11 12
| method Astrometry 17.875 Eclipse Timing Variations 315.360 Imaging 40.395 Microlensing 3840.000 Orbital Brightness Modulation 1180.000 Pulsar Timing 1200.000 Pulsation Timing Variations NaN Radial Velocity 40.445 Transit 341.000 Transit Timing Variations 855.000 Name: distance, dtype: float64
|
1 2 3 4
|
pd.set_option('display.max_rows', 40) df.groupby(['method', 'year'])['number'].sum()
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| method year Astrometry 2010 1 2013 1 Eclipse Timing Variations 2008 4 2009 1 2010 4 .. Transit 2014 93 Transit Timing Variations 2011 2 2012 2 2013 2 2014 3 Name: number, Length: 69, dtype: int64
|
1 2 3 4 5 6 7
|
df.drop('Before 2000', axis = 1, inplace = True)
grouped.apply(lambda x: x.max() - x.min())
|
1 2 3 4 5 6 7
|
import numpy as np
grouped.agg({'distance': [np.mean], 'number': [np.sum]})
|
四、参考资料
planets.csv 数据集下载