目录
本文的jupyter notebook脚本文件等从 百度网盘 下载
第三章 pandas库基础
3.1 数据结构
3.1.1 Series
Series 是带标签数据的一维数组 Series对象的创建
通用结构: pd.Series(data, index=index, dtype=dtype)
data:数据,可以是列表,字典或Numpy数组 index:索引,为可选参数 dtype: 数据类型,为可选参数
3.1.1.1 用列表创建
import pandas as pd
ser_obj = pd. Series( [ 'Python' , 'Java' , 'PHP' ] )
ser_obj
0 Python
1 Java
2 PHP
dtype: object
import pandas as pd
ser_obj = pd. Series( [ 'Python' , 'Java' , 'PHP' ] ,
index = [ 'one' , 'two' , 'three' ] )
ser_obj
one Python
two Java
three PHP
dtype: object
data = pd. Series( [ 1 , 2 , 3 , 4 ] , index= [ "a" , "b" , "c" , "d" ] )
data
a 1
b 2
c 3
d 4
dtype: int64
data = pd. Series( [ 1 , 2 , 3 , 4 ] , index= [ "a" , "b" , "c" , "d" ] , dtype= "float" )
data
a 1.0
b 2.0
c 3.0
d 4.0
dtype: float64
注意:数据支持多种类型
data = pd. Series( [ 1 , 2 , "3" , 4 ] , index= [ "a" , "b" , "c" , "d" ] )
data
a 1
b 2
c 3
d 4
dtype: object
data[ 'b' ]
2
data[ 'c' ]
'3'
3.1.1.2 用一维numpy数组创建
import numpy as np
x = np. arange( 5 )
pd. Series( x)
0 0
1 1
2 2
3 3
4 4
dtype: int32
3.1.1.3 用字典创建
population_dict = { "BeiJing" : 2154 ,
"ShangHai" : 2424 ,
"ShenZhen" : 1303 ,
"HangZhou" : 981 }
population = pd. Series( population_dict)
population
BeiJing 2154
ShangHai 2424
ShenZhen 1303
HangZhou 981
dtype: int64
字典创建,如果指定index,则会到字典的键中筛选,找不到的,值设为NaN
population = pd. Series( population_dict, index= [ "BeiJing" , "HangZhou" , "c" , "d" ] )
population
BeiJing 2154.0
HangZhou 981.0
c NaN
d NaN
dtype: float64
3.1.1.4 data为标量的情况
pd. Series( 5 , index= [ 100 , 200 , 300 ] )
100 5
200 5
300 5
dtype: int64
3.1.1.5 时间戳索引
import pandas as pd
from datetime import datetime
date_index = pd. to_datetime( [ '20180820' , '20180828' , '20180908' ] )
print ( date_index)
date_ser = pd. Series( [ 11 , 22 , 33 ] , index= date_index)
print ( date_ser)
DatetimeIndex(['2018-08-20', '2018-08-28', '2018-09-08'], dtype='datetime64[ns]', freq=None)
2018-08-20 11
2018-08-28 22
2018-09-08 33
dtype: int64
3.1.2 DataFrame
DataFrame 是带标签数据的多维数组
DataFrame对象的创建
通用结构: pd.DataFrame(data, index=index, columns=columns)
data:数据,可以是列表,字典或Numpy数组 index:索引,为可选参数 columns: 列标签,为可选参数
3.1.2.1 通过Series对象创建
population
BeiJing 2154.0
HangZhou 981.0
c NaN
d NaN
dtype: float64
population
BeiJing 2154
ShangHai 2424
ShenZhen 1303
HangZhou 981
dtype: int64
population_dict = { "BeiJing" : 2154 ,
"ShangHai" : 2424 ,
"ShenZhen" : 1303 ,
"HangZhou" : 981 }
population = pd. Series( population_dict)
pd. DataFrame( population)
0 BeiJing 2154 ShangHai 2424 ShenZhen 1303 HangZhou 981
3.1.2.2 通过字典创建
GDP_dict = { "BeiJing" : 30320 ,
"ShangHai" : 32680 ,
"ShenZhen" : 24222 ,
"HangZhou" : 13468 }
GDP = pd. Series( GDP_dict)
GDP
BeiJing 30320
ShangHai 32680
ShenZhen 24222
HangZhou 13468
dtype: int64
population
BeiJing 2154
ShangHai 2424
ShenZhen 1303
HangZhou 981
dtype: int64
pd. DataFrame( { "population" : population,
"GDP" : GDP} )
population GDP BeiJing 2154 30320 ShangHai 2424 32680 ShenZhen 1303 24222 HangZhou 981 13468
若行索引index不一致时
GDP_dict2 = { "BeiJing" : 30320 ,
"ShangHai" : 32680 ,
"ShenZhen" : 24222 ,
"HangZhou" : 13468 ,
"Chongqing" : 10000 }
GDP2 = pd. Series( GDP_dict2)
GDP2
BeiJing 30320
ShangHai 32680
ShenZhen 24222
HangZhou 13468
Chongqing 10000
dtype: int64
population
BeiJing 2154
ShangHai 2424
ShenZhen 1303
HangZhou 981
dtype: int64
pd. DataFrame( { "population" : population,
"GDP" : GDP2} )
population GDP BeiJing 2154.0 30320 Chongqing NaN 10000 HangZhou 981.0 13468 ShangHai 2424.0 32680 ShenZhen 1303.0 24222
注意:标量时会自动补齐
pd. DataFrame( { "population" : population,
"GDP" : GDP,
"country" : "China" } )
population GDP country BeiJing 2154 30320 China ShangHai 2424 32680 China ShenZhen 1303 24222 China HangZhou 981 13468 China
3.1.2.3 通过字典列表对象创建
import numpy as np
import pandas as pd
data = [ { "a" : i, "b" : 2 * i} for i in range ( 3 ) ]
data
[{'a': 0, 'b': 0}, {'a': 1, 'b': 2}, {'a': 2, 'b': 4}]
data = pd. DataFrame( data)
data
data = [ { "a" : 1 , "b" : 1 } , { "b" : 3 , "c" : 4 } ]
pd. DataFrame( data)
3.1.2.4 通过Numpy二维数组创建**
import numpy as np
import pandas as pd
demo_arr = np. array( [ [ 'a' , 'b' , 'c' ] , [ 'd' , 'e' , 'f' ] ] )
df_obj = pd. DataFrame( demo_arr)
df_obj
df_obj = pd. DataFrame( demo_arr, index = [ 'row_01' , 'row_02' ] ,
columns= [ 'col_01' , 'col_02' , 'col_03' ] )
df_obj
col_01 col_02 col_03 row_01 a b c row_02 d e f
3.2 DataFrame属性
data = pd. DataFrame( { "population" : population,
"GDP" : GDP} )
data
population GDP BeiJing 2154 30320 ShangHai 2424 32680 ShenZhen 1303 24222 HangZhou 981 13468
3.2.1 .values返回numpy数组表示的数据
data. values
array([[ 2154, 30320],
[ 2424, 32680],
[ 1303, 24222],
[ 981, 13468]], dtype=int64)
type ( data. values)
numpy.ndarray
3.2.2 .index返回行索引
data. index
Index(['BeiJing', 'ShangHai', 'ShenZhen', 'HangZhou'], dtype='object')
type ( data. index)
pandas.core.indexes.base.Index
3.2.3 .columns返回列索引
data. columns
Index(['population', 'GDP'], dtype='object')
type ( data. columns)
pandas.core.indexes.base.Index
3.2.4 .shape返回形状
data. shape
(4, 2)
3.2.5 .size 元素的个数
data. size
8
3.2.6 .dtypes 返回每列数据类型
data. dtypes
population int64
GDP int64
dtype: object
3.3 索引操作
3.3.1 索引对象
data
population GDP BeiJing 2154 30320 ShangHai 2424 32680 ShenZhen 1303 24222 HangZhou 981 13468
3.3.1.1 获取列
data[ 'GDP' ]
BeiJing 30320
ShangHai 32680
ShenZhen 24222
HangZhou 13468
Name: GDP, dtype: int64
type ( data[ 'GDP' ] )
pandas.core.series.Series
data[ [ 'GDP' ] ]
GDP BeiJing 30320 ShangHai 32680 ShenZhen 24222 HangZhou 13468
type ( data[ [ 'GDP' ] ] )
pandas.core.frame.DataFrame
data[ [ 'GDP' , 'population' ] ]
GDP population BeiJing 30320 2154 ShangHai 32680 2424 ShenZhen 24222 1303 HangZhou 13468 981
data. GDP
BeiJing 30320
ShangHai 32680
ShenZhen 24222
HangZhou 13468
Name: GDP, dtype: int64
data. population
BeiJing 2154
ShangHai 2424
ShenZhen 1303
HangZhou 981
Name: population, dtype: int64
3.3.1.2 获取行
绝对索引 df.loc[索引名]
.loc[索引名] 索引名是自己定义的绝对名称
data
population GDP BeiJing 2154 30320 ShangHai 2424 32680 ShenZhen 1303 24222 HangZhou 981 13468
data. loc[ 'BeiJing' ]
population 2154
GDP 30320
Name: BeiJing, dtype: int64
for ind in data. index:
print ( ind)
print ( data. loc[ ind] )
print ( "=" * 30 )
BeiJing
population 2154
GDP 30320
Name: BeiJing, dtype: int64
==============================
ShangHai
population 2424
GDP 32680
Name: ShangHai, dtype: int64
==============================
ShenZhen
population 1303
GDP 24222
Name: ShenZhen, dtype: int64
==============================
HangZhou
population 981
GDP 13468
Name: HangZhou, dtype: int64
==============================
相对索引 df.iloc[整数相对索引值]
.iloc[ ] 中括号内是整数索引值
data
population GDP BeiJing 2154 30320 ShangHai 2424 32680 ShenZhen 1303 24222 HangZhou 981 13468
data. iloc[ 0 ]
population 2154
GDP 30320
Name: BeiJing, dtype: int64
for i in range ( len ( data. index) ) :
print ( data. index[ i] )
print ( data. iloc[ i] )
print ( "=" * 30 )
BeiJing
population 2154
GDP 30320
Name: BeiJing, dtype: int64
==============================
ShangHai
population 2424
GDP 32680
Name: ShangHai, dtype: int64
==============================
ShenZhen
population 1303
GDP 24222
Name: ShenZhen, dtype: int64
==============================
HangZhou
population 981
GDP 13468
Name: HangZhou, dtype: int64
==============================
3.3.1.3 获取标量
data
population GDP BeiJing 2154 30320 ShangHai 2424 32680 ShenZhen 1303 24222 HangZhou 981 13468
data. loc[ 'BeiJing' , 'GDP' ]
30320
data. loc[ 'BeiJing' ] [ 'GDP' ]
30320
data. loc[ "BeiJing" ]
population 2154
GDP 30320
Name: BeiJing, dtype: int64
data. iloc[ 0 , 1 ]
30320
data. iloc[ 0 ] [ 1 ]
30320
data. at[ "BeiJing" , 'GDP' ]
30320
data. iat[ 0 , 1 ]
30320
3.3.2 切片
dates = pd. date_range( start= '2019-01-01' , periods= 6 )
dates
DatetimeIndex(['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04',
'2019-01-05', '2019-01-06'],
dtype='datetime64[ns]', freq='D')
df = pd. DataFrame( np. random. randn( 6 , 4 ) , index= dates, columns= [ "A" , "B" , "C" , "D" ] )
df
A B C D 2019-01-01 -0.631020 -0.621969 0.810936 0.631151 2019-01-02 -0.693042 1.845378 0.617447 0.282174 2019-01-03 -0.469042 0.448770 1.309556 -0.872601 2019-01-04 -0.070832 1.218591 0.352382 0.283966 2019-01-05 0.132611 1.828863 -1.035517 0.491823 2019-01-06 0.892035 -1.230534 -1.454877 -0.237451
3.3.2.1 行切片
df[ "2019-01-01" : "2019-01-03" ]
A B C D 2019-01-01 -0.631020 -0.621969 0.810936 0.631151 2019-01-02 -0.693042 1.845378 0.617447 0.282174 2019-01-03 -0.469042 0.448770 1.309556 -0.872601
df[ "2019-01-01" : "2019-01-05" : 2 ]
A B C D 2019-01-01 -0.631020 -0.621969 0.810936 0.631151 2019-01-03 -0.469042 0.448770 1.309556 -0.872601 2019-01-05 0.132611 1.828863 -1.035517 0.491823
df. loc[ "2019-01-01" : "2019-01-03" ]
A B C D 2019-01-01 -0.631020 -0.621969 0.810936 0.631151 2019-01-02 -0.693042 1.845378 0.617447 0.282174 2019-01-03 -0.469042 0.448770 1.309556 -0.872601
df. iloc[ 0 : 3 ]
A B C D 2019-01-01 -0.631020 -0.621969 0.810936 0.631151 2019-01-02 -0.693042 1.845378 0.617447 0.282174 2019-01-03 -0.469042 0.448770 1.309556 -0.872601
df. iloc[ 0 : 5 : 2 ]
A B C D 2019-01-01 -0.631020 -0.621969 0.810936 0.631151 2019-01-03 -0.469042 0.448770 1.309556 -0.872601 2019-01-05 0.132611 1.828863 -1.035517 0.491823
3.3.2.2 列切片
df
A B C D 2019-01-01 -0.631020 -0.621969 0.810936 0.631151 2019-01-02 -0.693042 1.845378 0.617447 0.282174 2019-01-03 -0.469042 0.448770 1.309556 -0.872601 2019-01-04 -0.070832 1.218591 0.352382 0.283966 2019-01-05 0.132611 1.828863 -1.035517 0.491823 2019-01-06 0.892035 -1.230534 -1.454877 -0.237451
df. loc[ : , "A" : "C" ]
A B C 2019-01-01 -0.631020 -0.621969 0.810936 2019-01-02 -0.693042 1.845378 0.617447 2019-01-03 -0.469042 0.448770 1.309556 2019-01-04 -0.070832 1.218591 0.352382 2019-01-05 0.132611 1.828863 -1.035517 2019-01-06 0.892035 -1.230534 -1.454877
df. loc[ : , "A" : "C" : 2 ]
A C 2019-01-01 -0.631020 0.810936 2019-01-02 -0.693042 0.617447 2019-01-03 -0.469042 1.309556 2019-01-04 -0.070832 0.352382 2019-01-05 0.132611 -1.035517 2019-01-06 0.892035 -1.454877
df. iloc[ : , 0 : 3 : 2 ]
A C 2019-01-01 -0.631020 0.810936 2019-01-02 -0.693042 0.617447 2019-01-03 -0.469042 1.309556 2019-01-04 -0.070832 0.352382 2019-01-05 0.132611 -1.035517 2019-01-06 0.892035 -1.454877
3.3.2.3 花式切片
df. loc[ "2019-01-02" : "2019-01-03" , "C" : "D" ]
C D 2019-01-02 0.617447 0.282174 2019-01-03 1.309556 -0.872601
df. iloc[ 1 : 3 , 2 : ]
C D 2019-01-02 0.617447 0.282174 2019-01-03 1.309556 -0.872601
df. loc[ "2019-01-04" : "2019-01-06" , [ "A" , "C" ] ]
A C 2019-01-04 -0.070832 0.352382 2019-01-05 0.132611 -1.035517 2019-01-06 0.892035 -1.454877
df. iloc[ 3 : , [ 0 , 2 ] ]
A C 2019-01-04 -0.070832 0.352382 2019-01-05 0.132611 -1.035517 2019-01-06 0.892035 -1.454877
df. loc[ [ "2019-01-02" , "2019-01-06" ] , "C" : "D" ]
C D 2019-01-02 0.617447 0.282174 2019-01-06 -1.454877 -0.237451
df. loc[ [ "2019-01-04" , "2019-01-06" ] , [ "A" , "D" ] ]
A D 2019-01-04 -0.070832 0.283966 2019-01-06 0.892035 -0.237451
df. iloc[ [ 1 , 5 ] , [ 0 , 3 ] ]
A D 2019-01-02 -0.693042 0.282174 2019-01-06 0.892035 -0.237451
3.3.3 布尔索引
df
A B C D 2019-01-01 -0.631020 -0.621969 0.810936 0.631151 2019-01-02 -0.693042 1.845378 0.617447 0.282174 2019-01-03 -0.469042 0.448770 1.309556 -0.872601 2019-01-04 -0.070832 1.218591 0.352382 0.283966 2019-01-05 0.132611 1.828863 -1.035517 0.491823 2019-01-06 0.892035 -1.230534 -1.454877 -0.237451
df> 0
A B C D 2019-01-01 False False True True 2019-01-02 False True True True 2019-01-03 False True True False 2019-01-04 False True True True 2019-01-05 True True False True 2019-01-06 True False False False
df[ df > 0 ]
A B C D 2019-01-01 NaN NaN 0.810936 0.631151 2019-01-02 NaN 1.845378 0.617447 0.282174 2019-01-03 NaN 0.448770 1.309556 NaN 2019-01-04 NaN 1.218591 0.352382 0.283966 2019-01-05 0.132611 1.828863 NaN 0.491823 2019-01-06 0.892035 NaN NaN NaN
df. A > 0
2019-01-01 False
2019-01-02 False
2019-01-03 False
2019-01-04 False
2019-01-05 True
2019-01-06 True
Freq: D, Name: A, dtype: bool
df[ df. A> 0 ]
A B C D 2019-01-05 0.132611 1.828863 -1.035517 0.491823 2019-01-06 0.892035 -1.230534 -1.454877 -0.237451
df2 = df. copy( )
df2[ 'E' ] = [ 'one' , 'one' , 'two' , 'three' , 'four' , 'three' ]
df2
A B C D E 2019-01-01 -0.631020 -0.621969 0.810936 0.631151 one 2019-01-02 -0.693042 1.845378 0.617447 0.282174 one 2019-01-03 -0.469042 0.448770 1.309556 -0.872601 two 2019-01-04 -0.070832 1.218591 0.352382 0.283966 three 2019-01-05 0.132611 1.828863 -1.035517 0.491823 four 2019-01-06 0.892035 -1.230534 -1.454877 -0.237451 three
ind = df2[ "E" ] . isin( [ "two" , "four" ] )
ind
2019-01-01 False
2019-01-02 False
2019-01-03 True
2019-01-04 False
2019-01-05 True
2019-01-06 False
Freq: D, Name: E, dtype: bool
df2[ df2[ "E" ] . isin( [ "two" , "four" ] ) ]
A B C D E 2019-01-03 -0.469042 0.448770 1.309556 -0.872601 two 2019-01-05 0.132611 1.828863 -1.035517 0.491823 four
3.3.4 分层索引
3.3.4.1 分层索引的创建
from_tuples() 根据元组列表创建分层索引
from_arrays() 根据数组列表创建分层索引
from_product() 从集合的笛卡尔乘积中创建分层索引
from_frame() 根据DataFrame类对象创建分层索引
from_tuples() 根据元组列表创建分层索引
import pandas as pd
tuple_clo = [ ( 'ca' , 0 ) , ( 'ca' , 1 ) , ( 'cb' , 2 ) , ( 'cb' , 2 ) ]
tuple_row = [ ( 'ra' , 0 ) , ( 'ra' , 1 ) , ( 'rb' , 2 ) , ( 'rb' , 2 ) ]
multi_index_col = pd. MultiIndex. from_tuples( tuples= tuple_clo)
multi_index_row = pd. MultiIndex. from_tuples( tuples= tuple_row)
data = [ [ 'A' , 'B' , 'C' , 'D' ] , [ 'E' , 'F' , 'G' , 'H' ] ,
[ 'I' , 'J' , 'K' , 'L' ] , [ 'M' , 'N' , 'O' , 'P' ] ]
df = pd. DataFrame( data, index= multi_index_row, columns= multi_index_col)
df
ca cb 0 1 2 2 ra 0 A B C D 1 E F G H rb 2 I J K L 2 M N O P
tuple_clo
[('ca', 0), ('ca', 1), ('cb', 2), ('cb', 2)]
multi_index_col
MultiIndex([('ca', 0),
('ca', 1),
('cb', 2),
('cb', 2)],
)
from_arrays() 根据数组列表创建分层索引
arrays = [ [ 1 , 1 , 2 , 2 ] , [ 'red' , 'blue' , 'red' , 'blue' ] ]
multi_row = pd. MultiIndex. from_arrays( arrays, names= ( 'number' , 'color' ) )
multi_row
MultiIndex([(1, 'red'),
(1, 'blue'),
(2, 'red'),
(2, 'blue')],
names=['number', 'color'])
pd. DataFrame( data, index= multi_row)
0 1 2 3 number color 1 red A B C D blue E F G H 2 red I J K L blue M N O P
df = pd. DataFrame( [ [ 'HI' , 'Temp' ] , [ 'HI' , 'Precip' ] ,
. . . [ 'NJ' , 'Temp' ] , [ 'NJ' , 'Precip' ] ] ,
. . . columns= [ 'a' , 'b' ] )
df
a b 0 HI Temp 1 HI Precip 2 NJ Temp 3 NJ Precip
from_frame() 根据DataFrame类对象创建分层索引
multi_index_row = pd. MultiIndex. from_frame( df)
multi_index_row
MultiIndex([('HI', 'Temp'),
('HI', 'Precip'),
('NJ', 'Temp'),
('NJ', 'Precip')],
names=['a', 'b'])
pd. DataFrame( data, index= multi_index_row)
0 1 2 3 a b HI Temp A B C D Precip E F G H NJ Temp I J K L Precip M N O P
from_product() 根据两个列表的笛卡尔积方式创建
data = np. random. randint( 0 , 100 , size= ( 6 , 3 ) )
names = [ '张三' , '李四' , '王五' ]
exam = [ '期中' , '期末' ]
index = pd. MultiIndex. from_product( [ names, exam] )
df = pd. DataFrame( data, index= index, columns= [ 'Java' , 'Web' , 'Python' ] )
df
Java Web Python 张三 期中 20 27 56 期末 82 21 86 李四 期中 0 11 23 期末 58 19 26 王五 期中 88 76 76 期末 98 29 31
3.3.4.2 使用分层索引访问数据
mult_series = pd. Series( [ 95 , 103 , 80 , 80 , 90 , 91 , 91 ] ,
index= [ [ '计算机专业' , '计算机专业' , '计算机专业' , '计算机专业' ,
'体育专业' , '体育专业' , '体育专业' ] ,
[ '物联网工程' , '软件工程' , '网络安全' , '信息安全' ,
'体育教育' , '休闲体育' , '运动康复' ] ] )
mult_series
计算机专业 物联网工程 95
软件工程 103
网络安全 80
信息安全 80
体育专业 体育教育 90
休闲体育 91
运动康复 91
dtype: int64
计算机专业 物联网工程 95
软件工程 103
网络安全 80
信息安全 80
体育专业 体育教育 90
休闲体育 91
运动康复 91
mult_series[ "计算机专业" ]
物联网工程 95
软件工程 103
网络安全 80
信息安全 80
dtype: int64
mult_series[ "计算机专业" ] [ "网络安全" ]
80
mult_series[ "体育专业" ]
体育教育 90
休闲体育 91
运动康复 91
dtype: int64
type ( mult_series)
pandas.core.series.Series
print ( mult_series[ '计算机专业' ] )
物联网工程 95
软件工程 103
网络安全 80
信息安全 80
dtype: int64
print ( mult_series[ '计算机专业' ] [ '软件工程' ] )
103
import numpy as np
arrays = [ 'a' , 'a' , 'b' , 'b' ] , [ 1 , 2 , 1 , 2 ]
frame = pd. DataFrame( np. arange( 12 ) . reshape( ( 4 , 3 ) ) ,
index= pd. MultiIndex. from_arrays( arrays) ,
columns= [ [ 'A' , 'A' , 'B' ] ,
[ 'Green' , 'Red' , 'Green' ] ] )
print ( frame)
A B
Green Red Green
a 1 0 1 2
2 3 4 5
b 1 6 7 8
2 9 10 11
frame[ "A" ]
frame[ "A" ] [ "Green" ]
a 1 0
2 3
b 1 6
2 9
Name: Green, dtype: int32
frame[ "B" ]
print ( frame[ 'A' ] )
Green Red
a 1 0 1
2 3 4
b 1 6 7
2 9 10
print ( frame[ 'A' ] [ 'Green' ] )
a 1 0
2 3
b 1 6
2 9
Name: Green, dtype: int32
frame
A B Green Red Green a 1 0 1 2 2 3 4 5 b 1 6 7 8 2 9 10 11
frame. loc[ "a" , "A" ]
frame. loc[ "a" ] [ "A" ]
frame. loc[ "a" ] [ "A" ] [ "Green" ]
1 0
2 3
Name: Green, dtype: int32
( frame. loc[ "a" ] [ "A" ] ) . loc[ 1 ]
Green 0
Red 1
Name: 1, dtype: int32
frame. loc[ "a" ]
print ( frame. loc[ 'a' ] )
A B
Green Red Green
1 0 1 2
2 3 4 5
print ( frame. loc[ 'a' , 'A' ] )
Green Red
1 0 1
2 3 4
frame
A B Green Red Green a 1 0 1 2 2 3 4 5 b 1 6 7 8 2 9 10 11
frame. iloc[ 2 ]
A Green 6
Red 7
B Green 8
Name: (b, 1), dtype: int32
3.3.5 重新索引
import pandas as pd
from pandas import Series, DataFrame
obj = Series( [ 4.5 , 7.2 , - 5.3 , 3.6 ] , index = [ 'd' , 'b' , 'a' , 'c' ] )
obj
d 4.5
b 7.2
a -5.3
c 3.6
dtype: float64
obj2 = obj. reindex( [ 'a' , 'b' , 'c' , 'd' , 'e' ] )
obj2
a -5.3
b 7.2
c 3.6
d 4.5
e NaN
dtype: float64
obj. reindex( [ 'a' , 'b' , 'c' , 'd' , 'e' ] , fill_value = 9.9 )
a -5.3
b 7.2
c 3.6
d 4.5
e 9.9
dtype: float64
obj3 = Series( [ 'blue' , 'purple' , 'yellow' ] , index = [ 0 , 2 , 4 ] )
obj3
0 blue
2 purple
4 yellow
dtype: object
obj3. reindex( range ( 6 ) , method = 'ffill' )
0 blue
1 blue
2 purple
3 purple
4 yellow
5 yellow
dtype: object
index = [ 'Firefox' , 'Chrome' , 'Safari' , 'IE10' , 'Konqueror' ]
df = pd. DataFrame( { 'http_status' : [ 200 , 200 , 404 , 404 , 301 ] ,
'response_time' : [ 0.04 , 0.02 , 0.07 , 0.08 , 1.0 ] } ,
index= index)
print ( '重新索引前:' )
print ( df)
print ( '--------------' )
new_index = [ 'Safari' , 'Iceweasel' , 'Comodo Dragon' , 'IE10' , 'Chrome' ]
new_df = df. reindex( new_index)
print ( '重新索引后:' )
print ( new_df)
重新索引前:
http_status response_time
Firefox 200 0.04
Chrome 200 0.02
Safari 404 0.07
IE10 404 0.08
Konqueror 301 1.00
--------------
重新索引后:
http_status response_time
Safari 404.0 0.07
Iceweasel NaN NaN
Comodo Dragon NaN NaN
IE10 404.0 0.08
Chrome 200.0 0.02
new_df = df. reindex( new_index, fill_value= 'missing' )
print ( new_df)
http_status response_time
Safari 404 0.07
Iceweasel missing missing
Comodo Dragon missing missing
IE10 404 0.08
Chrome 200 0.02
col_df = df. reindex( columns= [ 'http_status' , 'user_agent' ] )
print ( col_df)
http_status user_agent
Firefox 200 NaN
Chrome 200 NaN
Safari 404 NaN
IE10 404 NaN
Konqueror 301 NaN
3.3.6 切片获取的series或者dataframe是视图还是副本?
3.3.6.1 返回连续块的是视图
arr1 = np. random. randint( 0 , 100 , 12 ) . reshape( 3 , 4 )
df = pd. DataFrame( arr1, list ( "ABC" ) , list ( "abcd" ) )
df
a b c d A 10 44 39 85 B 54 77 41 40 C 51 3 36 88
ser1 = df[ 'a' ]
ser1
A 10
B 54
C 51
Name: a, dtype: int32
ser1[ "A" ] = 100
ser1
A 100
B 54
C 51
Name: a, dtype: int32
df
a b c d A 100 44 39 85 B 54 77 41 40 C 51 3 36 88
df2 = df. loc[ "A" : "B" , "a" : "c" ]
print ( type ( df2) )
df2
<class 'pandas.core.frame.DataFrame'>
df2. loc[ "B" , "b" ] = 888
df2
df
a b c d A 100 44 39 85 B 54 888 41 40 C 51 3 36 88
df22 = df. loc[ "A" : "B" , "a" : "c" ] . copy( )
print ( type ( df22) )
df22
<class 'pandas.core.frame.DataFrame'>
df22. loc[ "A" , "b" ] = 444
df22
df
a b c d A 100 44 39 85 B 54 888 41 40 C 51 3 36 88
3.3.6.2 花式索引得到的是副本
df31 = df. loc[ [ "A" , "C" ] , "a" : "c" ]
df31
df31. loc[ "C" , "b" ] = 333
df31
df31
df
a b c d A 100 44 39 85 B 54 888 41 40 C 51 3 36 88
df3 = df. loc[ [ "A" , "C" ] , [ "a" , "c" ] ]
print ( type ( df3) )
df3
<class 'pandas.core.frame.DataFrame'>
df3. iloc[ 1 , 1 ] = 999
df3
df
a b c d A 100 44 39 85 B 54 888 41 40 C 51 3 36 88
3.4 数据处理常用的操作:增、删、查、改
3.4.1 增
3.4.1.1 增加行
arr = np. arange( 9 )
ar = arr. reshape( 3 , 3 )
df = pd. DataFrame( ar)
df
df. loc[ 6 ] = [ 'a' , 'b' , 'c' ]
df
df0 = pd. DataFrame( [ 6 , 6 , 6 ] ) . T
df0
pd. concat( [ df, df0] , ignore_index= False )
pd. concat( [ df, df0] , ignore_index= True )
df1 = pd. concat( [ df, df0] , ignore_index= True )
df1
df0. iloc[ 0 , 1 ] = 666
df0
df1
3.4.1.2 增加列
增加一列很简单,类似于字典,若存在则覆盖,没有则新增一列,前提是该列与已有的列长度相等。
df
df[ 'new' ] = [ 'a' , 'b' , 'c' , 'd' ]
df
0 1 2 new 0 0 1 2 a 1 3 4 5 b 2 6 7 8 c 6 a b c d
df. insert( 2 , 'colunm_b' , [ 4 , 0 , 2 , 1 ] )
df
0 1 colunm_b 2 new 0 0 1 4 2 a 1 3 4 0 5 b 2 6 7 2 8 c 6 a b 1 c d
3.4.2 删
3.4.2.1 删除列
df
0 1 colunm_b 2 new 0 0 1 4 2 a 1 3 4 0 5 b 2 6 7 2 8 c 6 a b 1 c d
df. drop( 'colunm_b' , axis= 1 , inplace = True )
df
0 1 2 new 0 0 1 2 a 1 3 4 5 b 2 6 7 8 c 6 a b c d
df. drop( df. columns[ [ 0 , 1 ] ] , axis= 1 , inplace= False )
df
0 1 2 new 0 0 1 2 a 1 3 4 5 b 2 6 7 8 c 6 a b c d
3.4.2.2 删除行
df. drop( 1 , axis= 0 , inplace = False )
df
df. drop( df. index[ 3 ] , inplace = True )
df
df. drop( df. index[ [ 1 , 2 ] ] , inplace = False )
df
df[ ~ df[ 'new' ] . str . contains( 'c' ) ]
df
df[ df[ 'new' ] != 'c' ]
3.4.3 查
3.4.3.1 在某列或者全局中查找某个具体的值
d = { 'a' : [ 1 , 2 , 3 , 2 ] , 'b' : [ 0 , 2 , 1 , 2 ] , 'c' : [ 0 , 2 , 1 , 2 ] }
df = pd. DataFrame( d)
df
df[ df[ 'a' ] == 3 ]
np. where( df== 3 )
(array([2], dtype=int64), array([0], dtype=int64))
df== 3
a b c 0 False False False 1 False False False 2 True False False 3 False False False
3.4.3.2 查找空值
d = { 'a' : [ 1 , 2 , 3 , 2 ] , 'b' : [ 0 , 2 , 1 , 2 ] , 'c' : [ 0 , 2 , np. NAN, 2 ] }
df = pd. DataFrame( d)
df
a b c 0 1 0 0.0 1 2 2 2.0 2 3 1 NaN 3 2 2 2.0
np. where( np. isnan( df) )
(array([2], dtype=int64), array([2], dtype=int64))
3.4.3.3 定位重复数据
DataFrame.duplicated(self,subset = None,keep =‘first’) 返回表示重复行的布尔Series,可以选择仅考虑某些列。 参数:
subset: 列标签或标签序列,可选 仅考虑某些列来标识重复项,默认情况下使用所有列 keep: {‘first’,‘last’,False},默认为’first’
first:将重复项标记True为第一次出现的除外。 last:将重复项标记True为最后一次除外。 False:将所有重复项标记为True。
返回:Series
df
a b c 0 1 0 0.0 1 2 2 2.0 2 3 1 NaN 3 2 2 2.0
df_0 = df. duplicated( 'a' )
df_0
0 False
1 False
2 False
3 True
dtype: bool
df_1 = df. duplicated( 'a' , keep= "last" )
df_1
0 False
1 True
2 False
3 False
dtype: bool
df_0= df_0[ df_0]
df_0
3 True
dtype: bool
3.4.3.4 删除重复数据
使用drop_duplicates方法
DataFrame.drop_duplicates(subset=None, keep=‘first’, inplace=False)
subset参数:根据哪个字段进行重复筛选(多个字段就写成列表形式) inplace参数:是否在原数据集更改 keep参数:是从头开始筛选还是从末尾数据开始筛选({‘first’, ‘last’, False}, default ‘first’)
df
a b c 0 1 0 0.0 1 2 2 2.0 2 3 1 NaN 3 2 2 2.0
df. drop( 3 , axis= 0 , inplace = False )
3.4.3.5 利用ix查询
pandas中有iloc、loc、ix数据提取方法,其中
iloc:是位置索引 loc:是标签索引 ix:结合了iloc和loc的用法,首先会尝试loc一样的行为,如果索引中不存在标签,则会退回iloc一样的行为 但是已经不建议使用ix
3.4.4 改
改数据则是能够访问到元素的时候,进行赋值即可。 .astype()将一列的数据类型
3.4.4.1 更改数据值
data = [ [ "1" , 11 , 12 ] ,
[ "2" , 21 , 22 ] ,
[ "3" , 31 , 32 ] ,
[ "4" , 41 , 42 ] ]
df = pd. DataFrame( data, list ( "ABCD" ) , list ( "abc" ) )
df
a b c A 1 11 12 B 2 21 22 C 3 31 32 D 4 41 42
df. loc[ "A" , "a" ] = "11"
df
a b c A 11 11 12 B 2 21 22 C 3 31 32 D 4 41 42
df[ 'a' ] = [ '1' , '2' , '3' , '4' ]
df
a b c A 1 11 12 B 2 21 22 C 3 31 32 D 4 41 42
df. loc[ 'D' ] = [ "4" , 41 , 420 ]
df
a b c A 1 11 12 B 2 21 22 C 3 31 32 D 4 41 420
3.4.4.2 更改数据类型
df[ "a" ] + df[ "b" ]
df. info( )
<class 'pandas.core.frame.DataFrame'>
Index: 4 entries, A to D
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 a 4 non-null object
1 b 4 non-null int64
2 c 4 non-null int64
dtypes: int64(2), object(1)
memory usage: 300.0+ bytes
df[ "a" ] = df[ "a" ] . astype( "int64" )
df. info( )
<class 'pandas.core.frame.DataFrame'>
Index: 4 entries, A to D
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 a 4 non-null int64
1 b 4 non-null int64
2 c 4 non-null int64
dtypes: int64(3)
memory usage: 300.0+ bytes
df[ "a" ] + df[ "b" ]
A 12
B 23
C 34
D 45
dtype: int64
3.4.4.3 更改索引名称
df
a b c A 1 11 12 B 2 21 22 C 3 31 32 D 4 41 420
df. index = [ i for i in range ( len ( df) ) ]
df
a b c 0 1 11 12 1 2 21 22 2 3 31 32 3 4 41 420
df. columns = [ i for i in range ( df. shape[ 1 ] ) ]
df
0 1 2 0 1 11 12 1 2 21 22 2 3 31 32 3 4 41 420
3.5 数据排序
3.5.1 按索引排序
格式:
sort_index( axis= 0 , level= None , ascending= True , inplace= False ,
kind= 'quicksort' , na_position= 'last' , sort_remaining= True ,
ignore_index: bool = False )
参数:
axis:{0 或 ‘index’, 1 或 ‘columns’}, 默认为 0排序的轴(axis)。值0表示行,1表示列。 level :int 或 level name 或 ints的list 或 level names的list,如果不为None,则按指定索引级别的值排序。 ascending :bool 或 bools的list, 默认为 True。升序和降序排序。当索引是多索引时,排序方向可以为每个级别单独控制。 inplace :bool, 默认为 False。如果为True,就地执行操作。 kind :{‘quicksort’, ‘mergesort’, ‘heapsort’},默认为 ‘quicksort’,选择排序算法。有关更多信息,请参见darray.np.sort。 mergesort是唯一稳定的算法。对于DataFrames,仅在对单个列或标签进行排序时才应用此选项。 na_position :{‘first’, ‘last’}, 默认为 ‘last’,如果首先将NaN放在开头; 最后将NaN放在最后。未针对MultiIndex实施。 sort_remaining :bool,默认为True。如果为True且按级别和索引排序是多层的,则在按指定级别排序后也按其他级别(按顺序)排序。 ignore_index :bool, 默认为 False。如果为True,则结果轴将标记为0、1,…,n-1。1.0.0版的新功能。 key:callable, 可选的,如果不是None,则在排序之前将key函数应用于索引值。这类似于内建函数中的key参数sorted(),
返回值: 原始DataFrame按标签排序。
import numpy as np
import pandas as pd
df = pd. DataFrame( np. arange( 9 ) . reshape( ( 3 , 3 ) ) ,
columns= [ 'c' , 'a' , 'b' ] , index= [ 'B' , 'C' , 'A' ] )
print ( df)
print ( '--------------' )
row_sort = df. sort_index( )
print ( row_sort)
c a b
B 0 1 2
C 3 4 5
A 6 7 8
--------------
c a b
A 6 7 8
B 0 1 2
C 3 4 5
df
df
df. sort_index( inplace= True )
col_sort = df. sort_index( axis= 1 )
col_sort
arrays = [ 'a' , 'a' , 'b' , 'b' ] , [ 5 , 2 , 3 , 1 ]
df2 = pd. DataFrame( np. arange( 12 ) . reshape( ( 4 , 3 ) ) ,
index= pd. MultiIndex. from_arrays( arrays) ,
columns= [ [ 'A' , 'A' , 'B' ] ,
[ 'Green' , 'Red' , 'Green' ] ] )
df2
A B Green Red Green a 5 0 1 2 2 3 4 5 b 3 6 7 8 1 9 10 11
df2. sort_index( level= 1 )
A B Green Red Green b 1 9 10 11 a 2 3 4 5 b 3 6 7 8 a 5 0 1 2
3.5.2 按值排序
格式:
DataFrame. sort_values( by,
axis= 0 ,
ascending= True ,
inplace= False ,
kind= 'quicksort' ,
na_position= 'last' ,
ignore_index= False , key= None )
import numpy as np
df = pd. DataFrame( { 'col_A' : [ 5 , 1 , 4 , 6 ] ,
'col_B' : [ 4 , np. nan, 4 , 2 ] ,
'col_C' : [ 6 , 3 , 8 , 0 ] } )
df
col_A col_B col_C 0 5 4.0 6 1 1 NaN 3 2 4 4.0 8 3 6 2.0 0
new_df = df. sort_values( by= 'col_B' )
new_df
col_A col_B col_C 3 6 2.0 0 0 5 4.0 6 2 4 4.0 8 1 1 NaN 3
new_df2 = df. sort_values( by= [ 'col_B' , 'col_A' ] )
new_df2
col_A col_B col_C 3 6 2.0 0 2 4 4.0 8 0 5 4.0 6 1 1 NaN 3
new_df3 = df. sort_values( by= [ 'col_B' , 'col_A' ] , ascending= [ True , False ] )
new_df3
col_A col_B col_C 3 6 2.0 0 0 5 4.0 6 2 4 4.0 8 1 1 NaN 3
df. sort_values( by= 'col_B' , na_position= 'first' )
col_A col_B col_C 1 1 NaN 3 3 6 2.0 0 0 1 4.0 6 2 4 4.0 8
3.6 统计计算于统计描述
3.6.1 数据总览查看
DataFrame.head() DataFrame.tail() DataFrame.describe() DataFrame.info()
score = np. random. randint( 60 , 100 , 60 ) . reshape( 12 , 5 )
studentNames = [ "李思艺" ,
"刘昕" ,
"朱银莎" ,
"张德荣" ,
"张维涛" ,
"牟伦聪" ,
"谭汶江" ,
"唐周润" ,
"张淑琪" ,
"宋越" ,
"曾尧" ,
"李良鱼" ]
cousreNames = [ 'python' , 'c' , 'java' , 'math' , 'English' ]
scoreOfClass1 = pd. DataFrame( score, index = studentNames, columns= cousreNames)
scoreOfClass1
python c java math English 李思艺 96 76 73 77 65 刘昕 79 95 95 87 92 朱银莎 63 61 73 88 90 张德荣 87 94 67 85 84 张维涛 98 67 61 66 97 牟伦聪 77 78 89 95 74 谭汶江 96 62 63 91 63 唐周润 69 67 94 73 97 张淑琪 66 72 87 84 87 宋越 96 95 97 77 98 曾尧 93 73 91 63 91 李良鱼 83 71 61 60 80
3.6.1.1 查看前面的行 .head()
scoreOfClass1. head( )
python c java math English 李思艺 96 76 73 77 65 刘昕 79 95 95 87 92 朱银莎 63 61 73 88 90 张德荣 87 94 67 85 84 张维涛 98 67 61 66 97
scoreOfClass1. head( 3 )
python c java math English 李思艺 96 76 73 77 65 刘昕 79 95 95 87 92 朱银莎 63 61 73 88 90
3.6.1.2 查看后面的行.tail()
scoreOfClass1. tail( )
python c java math English 唐周润 69 67 94 73 97 张淑琪 66 72 87 84 87 宋越 96 95 97 77 98 曾尧 93 73 91 63 91 李良鱼 83 71 61 60 80
scoreOfClass1. tail( 3 )
python c java math English 宋越 96 95 97 77 98 曾尧 93 73 91 63 91 李良鱼 83 71 61 60 80
3.6.1.3 查看数据的总体信息 .info()
scoreOfClass1. info( )
<class 'pandas.core.frame.DataFrame'>
Index: 12 entries, 李思艺 to 李良鱼
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 python 12 non-null int32
1 c 12 non-null int32
2 java 12 non-null int32
3 math 12 non-null int32
4 English 12 non-null int32
dtypes: int32(5)
memory usage: 336.0+ bytes
3.6.1.4 查看数据的统计信息描述 .describe()
scoreOfClass1. describe( )
python c java math English count 12.000000 12.000000 12.000000 12.000000 12.000000 mean 83.583333 75.916667 79.250000 78.833333 84.833333 std 12.724053 12.369011 14.245414 11.424323 12.066734 min 63.000000 61.000000 61.000000 60.000000 63.000000 25% 75.000000 67.000000 66.000000 71.250000 78.500000 50% 85.000000 72.500000 80.000000 80.500000 88.500000 75% 96.000000 82.000000 91.750000 87.250000 93.250000 max 98.000000 95.000000 97.000000 95.000000 98.000000
3.6.2 常见的统计计算
count() 计算非NAN值的个数 sum() 计算和 mean() 计算平均值 max()、min() 计算最大值、最小值 idxmax()、idxmin() 计算最大索引值、最小索引值 var() 计算样本值的方差 std() 计算样本值的标准差 cumsum()、cumprod() 计算样本值的累计和、样本值的累计积 cummin()、cummax() 计算样本值累计最小值、样本值累计最大值
说明: 其中的参数skipna=True表示nan不计入
3.6.2.1 计算非nan值的个数 .count()
scoreOfClass1. count( )
python 12
c 12
java 12
math 12
English 12
dtype: int64
3.6.2.2 计算和 .sum()
scoreOfClass1. sum ( axis= 1 , skipna= True )
李思艺 387
刘昕 448
朱银莎 375
张德荣 417
张维涛 389
牟伦聪 413
谭汶江 375
唐周润 400
张淑琪 396
宋越 463
曾尧 411
李良鱼 355
dtype: int64
3.6.2.3 计算平均值 .mean()
scoreOfClass1. mean( axis= 1 )
李思艺 77.4
刘昕 89.6
朱银莎 75.0
张德荣 83.4
张维涛 77.8
牟伦聪 82.6
谭汶江 75.0
唐周润 80.0
张淑琪 79.2
宋越 92.6
曾尧 82.2
李良鱼 71.0
dtype: float64
scoreOfClass1. mean( )
python 83.583333
c 75.916667
java 79.250000
math 78.833333
English 84.833333
dtype: float64
3.6.2.4 计算最大值.max()、最小值.min()
scoreOfClass1. max ( )
python 98
c 95
java 97
math 95
English 98
dtype: int32
scoreOfClass1. min ( )
python 63
c 61
java 61
math 60
English 63
dtype: int32
3.6.2.5 计算最大索引值.idxmax()、最小索引值idxmin()
scoreOfClass1. idxmax( axis = 0 )
python 张维涛
c 刘昕
java 宋越
math 牟伦聪
English 宋越
dtype: object
scoreOfClass1. idxmax( axis= 'columns' )
李思艺 python
刘昕 c
朱银莎 English
张德荣 c
张维涛 python
牟伦聪 math
谭汶江 python
唐周润 English
张淑琪 java
宋越 English
曾尧 python
李良鱼 python
dtype: object
scoreOfClass1. idxmin( axis = 'index' )
python 朱银莎
c 朱银莎
java 张维涛
math 李良鱼
English 谭汶江
dtype: object
scoreOfClass1. idxmin( axis= 'columns' )
李思艺 English
刘昕 python
朱银莎 c
张德荣 java
张维涛 java
牟伦聪 English
谭汶江 c
唐周润 c
张淑琪 python
宋越 math
曾尧 math
李良鱼 math
dtype: object
3.6.2.6 计算方差.var()
scoreOfClass1. var( )
python 161.901515
c 152.992424
java 202.931818
math 130.515152
English 145.606061
dtype: float64
3.6.2.7 计算标准差.std()
scoreOfClass1. std( )
python 12.724053
c 12.369011
java 14.245414
math 11.424323
English 12.066734
dtype: float64
3.6.2.8 计算样本值的累计和cumsum()、样本值的累计积cumprod()
numpy也支持
a= np. array( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] )
a
array([[1, 2, 3],
[4, 5, 6]])
np. cumsum( a)
array([ 1, 3, 6, 10, 15, 21], dtype=int32)
np. cumprod( a)
array([ 1, 2, 6, 24, 120, 720], dtype=int32)
df = pd. DataFrame( [ [ 2.0 , 1.0 , 3 ] ,
[ 3.0 , np. nan, 4 ] ,
[ 1.0 , 0.0 , 5 ] ] ,
columns= list ( 'ABC' ) )
df
A B C 0 2.0 1.0 3 1 3.0 NaN 4 2 1.0 0.0 5
df. cumsum( )
A B C 0 2.0 1.0 3 1 5.0 NaN 7 2 6.0 1.0 12
df
A B C 0 2.0 1.0 3 1 3.0 NaN 4 2 1.0 0.0 5
df. cumsum( axis= 1 )
A B C 0 2.0 3.0 6.0 1 3.0 NaN 7.0 2 1.0 1.0 6.0
cumprod()类似
df. cumprod( )
A B C 0 2.0 1.0 3 1 6.0 NaN 12 2 6.0 0.0 60
df. cumprod( axis= 'columns' )
A B C 0 2.0 2.0 6.0 1 3.0 NaN 12.0 2 1.0 0.0 0.0
3.7 绘制图表
import pandas as pd
df = pd. DataFrame( { '商品A' : [ 2 , 34 , 25 , 4 ] ,
'商品B' : [ 1 , 3 , 45 , 9 ] ,
'商品C' : [ 7 , 5 , 5 , 3 ] } ,
index= [ '第1季度' , '第2季度' , '第3季度' , '第4季度' ] )
df
商品A 商品B 商品C 第1季度 2 1 7 第2季度 34 3 5 第3季度 25 45 5 第4季度 4 9 3
df. plot( kind= 'bar' , xlabel= '季度' , ylabel= '销售额(万元)' , rot= 0 )
.....
画出来了,但感觉有点儿不对劲儿?? 汉字没有显示出来
3.7.1 中文字符显示设置
Pandas在绘图时,会显示中文为方块,主要原因有二: matplotlib 字体问题,seaborn 字体问题。 没有中文字体,所以我们只要手动添加中文字体的名称就可以了,不过并不是添加我们熟悉的“宋体”或“黑体”这类的名称,而是要添加字体管理器识别出的字体名称,matplotlib自身实现的字体管理器在文件font_manager.py中,自动生成的可用字体信息在保存在文件fontList.cache里,可以搜索这个文件查看对应字体的名称,例如simhei.ttf对应的名称为’SimHei’,simkai.ttf对应的名称为’KaiTi_GB2312’等。因此我们只要把这些名称添加到配置文件中去就可以让matplotlib显示中文。
import matplotlib. pyplot as plt
plt. rcParams[ 'font.sans-serif' ] = [ 'SimHei' ]
plt. rcParams[ 'font.serif' ] = [ 'SimHei' ]
plt. rcParams[ 'axes.unicode_minus' ] = False
import seaborn as sns
sns. set_style( "darkgrid" , { "font.sans-serif" : [ 'KaiTi' , 'Arial' ] } )
df. plot( kind= 'bar' , xlabel= '季度' , ylabel= '销售额(万元)' , rot= 0 )
3.7.2 DataFrame.plot()函数
一般格式:
DataFrame. plot( x= None , y= None , kind= 'line' , ax= None , subplots= False ,
sharex= None , sharey= False , layout= None , figsize= None ,
use_index= True , title= None , grid= None , legend= True ,
style= None , logx= False , logy= False , loglog= False ,
xticks= None , yticks= None , xlim= None , ylim= None , rot= None ,
fontsize= None , colormap= None , position= 0.5 , table= False , yerr= None ,
xerr= None , stacked= True / False , sort_columns= False ,
secondary_y= False , mark_right= True , ** kwds)
主要参数解释:
x : label or position, default None#指数据框列的标签或位置参数 y : label or position, default None kind : str
‘line’ : line plot (default)#折线图 ‘bar’ : vertical bar plot#条形图 ‘barh’ : horizontal bar plot#横向条形图 ‘hist’ : histogram#柱状图 ‘box’ : boxplot#箱线图 ‘kde’ : Kernel Density Estimation plot#Kernel 的密度估计图,主要对柱状图添加Kernel 概率密度线 ‘density’ : same as ‘kde’ ‘area’ : area plot#不了解此图 ‘pie’ : pie plot#饼图 ‘scatter’ : scatter plot#散点图 需要传入columns方向的索引 ‘hexbin’ : hexbin plot#不了解此图 ax : matplotlib axes object, default None#子图(axes, 也可以理解成坐标轴) 要在其上进行绘制的matplotlib subplot对象。如果没有设置,则使用当前matplotlib subplot 其中,变量和函数通过改变figure和axes中的元素(例如:title,label,点和线等等)一起描述figure和axes,也就是在画布上绘图。 subplots : boolean, default False#判断图片中是否有子图 Make separate subplots for each column sharex : boolean, default True if ax is None else False#如果有子图,子图共x轴刻度,标签 In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in; Be aware, that passing in both an ax and sharex=True will alter all x axis labels for all axis in a figure! sharey : boolean, default False#如果有子图,子图共y轴刻度,标签 In case subplots=True, share y axis and set some y axis labels to invisible layout : tuple (optional)#子图的行列布局 (rows, columns) for the layout of subplots figsize : a tuple (width, height) in inches#图片尺寸大小 use_index : boolean, default True#默认用索引做x轴 title : string#图片的标题用字符串 grid : boolean, default None (matlab style default)#图片是否有网格 Axis grid lines legend : False/True/’reverse’#子图的图例,添加一个subplot图例(默认为True) Place legend on axis subplots style : list or dict#对每列折线图设置线的类型 matplotlib line style per column logx : boolean, default False#设置x轴刻度是否取对数 Use log scaling on x axis logy : boolean, default False Use log scaling on y axis loglog : boolean, default False#同时设置x,y轴刻度是否取对数 Use log scaling on both x and y axes xticks : sequence#设置x轴刻度值,序列形式(比如列表) Values to use for the xticks yticks : sequence#设置y轴刻度,序列形式(比如列表) Values to use for the yticks xlim : 2-tuple/list#设置坐标轴的范围,列表或元组形式 ylim : 2-tuple/list rot : int, default None#设置轴标签(轴刻度)的显示旋转度数 Rotation for ticks (xticks for vertical, yticks for horizontal plots) fontsize : int, default None#设置轴刻度的字体大小 Font size for xticks and yticks colormap : str or matplotlib colormap object, default None#设置图的区域颜色 Colormap to select colors from. If string, load colormap with that name from matplotlib. colorbar : boolean, optional #图片柱子 If True, plot colorbar (only relevant for ‘scatter’ and ‘hexbin’ plots) position : float Specify relative alignments for bar plot layout. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center) layout : tuple (optional) #布局 (rows, columns) for the layout of the plot table : boolean, Series or DataFrame, default False #如果为正,则选择DataFrame类型的数据并且转换匹配matplotlib的布局。 If True, draw a table using the data in the DataFrame and the data will be transposed to meet matplotlib’s default layout. If a Series or DataFrame is passed, use passed data to draw a table. yerr : DataFrame, Series, array-like, dict and str See Plotting with Error Bars for detail. xerr : same types as yerr. stacked : boolean, default False in line and bar plots, and True in area plot. If True, create stacked plot. sort_columns : boolean, default False # 以字母表顺序绘制各列,默认使用前列顺序 secondary_y : boolean or sequence, default False ##设置第二个y轴(右y轴) Whether to plot on the secondary y-axis If a list/tuple, which columns to plot on secondary y-axis mark_right : boolean, default True When using a secondary_y axis, automatically mark the column labels with “(right)” in the legend kwds : keywords Options to pass to matplotlib plotting method Returns:axes : matplotlib.AxesSubplot or np.array of them
3.7.3 线形图
普通折线图以折线的上升或下降来表示统计数量的增减变化的统计图,叫作折线统计图。折线统计图不仅可以表示数量的多少,而且可以反映同一事物在不同时间里的发展变化的情况,虽然它不直接给出精确的数据(当然你也可以加上去),但是能够显示数据的变化趋势,反映事物的变化情况。
pandas 有两种绘制线形图的方法:
一种是前面介绍的DataFrame.plot() 另外一种是DataFrame.plot.line 推荐使用后一种,前一种在新的pandas版本中可能将取消
test_dict = { '销售量' : [ 1000 , 2000 , 5000 , 2000 , 4000 , 3000 ] , '收藏' : [ 1500 , 2300 , 3500 , 2400 , 1900 , 3000 ] }
df = pd. DataFrame( test_dict, index= [ '一月' , '二月' , '三月' , '四月' , '五月' , '六月' ] )
df. plot( ) ;
df. plot. line( ) ;
df. plot. line( subplots= True ) ;
3.7.4 条形图
条形统计图可以清楚地表明各种数量的多少。 条形图是统计图资料分析中最常用的图形。 按照排列方式的不同,可分为纵式条形图和横式条形图; 按照分析作用的不同,可分为条形比较图和条形结构图。
条形统计图的特点: (1)能够使人们一眼看出各个数据的大小。 (2)易于比较数据之间的差别。 (3)能清楚的表示出数量的多少
3.7.4.1 垂直条形图
df. plot( kind= 'bar' ) ;
df. plot. bar( ) ;
df. plot( kind= 'bar' , stacked= True ) ;
df. plot. bar( stacked= True ) ;
df. plot( kind= 'bar' , subplots= True , rot= 0 ) ;
df. plot. bar( subplots= True , rot= 0 ) ;
3.7.4.2 水平条形图
DataFrame.plot(kind=‘barh’) DataFrame.plot.barh()
df. plot( kind= 'barh' ) ;
df. plot. barh( title= "销售售业绩图" ) ;
3.7.5 饼图
适用场景:显示各项的大小与各项总和的比例。适用简单的占比比例图,在不要求数据精细的情况适用。
优势:明确显示数据的比例情况,尤其合适渠道来源分析等场景。
df. plot( kind= 'pie' ,
subplots= True ,
figsize= ( 10 , 8 ) ,
autopct= '%.2f%%' ,
radius = 1.2 ,
startangle = 250 ,
counterclock= False ,
legend= False ,
pctdistance = 0.8 ,
explode = ( 0 , 0 , 0.1 , 0 , 0 , 0 ) ,
shadow= True ,
colormap= 'viridis' ) ;
df. plot. pie( subplots= True ,
figsize= ( 10 , 8 ) ,
autopct= '%.2f%%' ,
radius = 1.2 ,
startangle = 250 ,
legend= False ,
colormap= 'viridis' ) ;
3.7.6 散点图
适用场景:显示若干数据系列中各数值之间的关系,类似XY轴,判断两变量之间是否存在某种关联。散点图适用于三维数据集,但其中只有两维需要比较。
优势:对于处理值的分布和数据点的分簇,散点图都很理想。如果数据集中包含非常多的点,那么散点图便是最佳图表类型。
3.7.6.1 普通散点图
df
销售量 收藏 一月 1000 1500 二月 2000 2300 三月 5000 3500 四月 2000 2400 五月 4000 1900 六月 3000 3000
df. plot( kind= 'scatter' , x= '收藏' , y= '销售量' ) ;
df. plot. scatter( x= '收藏' , y= '销售量' ) ;
3.7.6.2 气泡图
注 气泡(散点)作为大小值(三维关系)
test_dict1 = { '销售量' : [ 1000 , 2000 , 5000 , 2000 , 4000 , 3000 ] , '收藏' : [ 1500 , 2300 , 3500 , 2400 , 1900 , 3000 ] , '评价数' : [ 20 , 400 , 30 , 50 , 500 , 80 ] }
df1 = pd. DataFrame( test_dict1, index= [ '一月' , '二月' , '三月' , '四月' , '五月' , '六月' ] )
df1. plot. scatter( x= '收藏' , y= '销售量' , s= df1[ '评价数' ] ) ;
3.7.6.3 多组散点图
ax= df1. plot. scatter( x= '评价数' , y= '收藏' , label= '评价-收藏' , color= 'c' )
df1. plot. scatter( x= '评价数' , y= '销售量' , label= '评价-销售量' , ax= ax) ;
3.7.7 面积图
面积图又称区域图,强调数量随时间而变化的程度,也可用于引起人们对总值趋势的注意。 堆积面积图还可以显示部分与整体的关系。 折线图和面积图都可以用来帮助我们对趋势进行分析, 当数据集有合计关系或者你想要展示局部与整体关系的时候,使用面积图为更好的选择。
特点:
比折线图看起来更加美观。 能够突出每个系别所占据的面积,把握整体趋势。 不仅可以表示数量的多少,而且可以反映同一事物在不同时间里的发展变化的情况。 可以纵向与其他系别进行比较,能够直观地反映出差异。
3.7.7.1 一般面积图
df. plot. area( stacked= False ) ;
3.7.7.2 堆积图
df. plot. area( ) ;
3.7.8 箱线图
箱线图作为描述统计的工具之一,其功能有独特之处,主要有以下几点:
一般格式:
DataFrame. boxplot( self,
column= None ,
by= None ,
ax= None ,
fontsize= None ,
rot= 0 ,
grid= True ,
figsize= None ,
layout= None ,
return_type= None , ** kwds)
参数解释:
column : str或str的列表,可选,列名或名称列表或向量。 by : str或array-like,可选 DataFrame中的列。 ax : 类matplotlib.axes.Axes的对象,可选,由boxplot使用的matplotlib轴。 fontsize : float或str,以标记或字符串(例如,大)标记标签字体大小。 rot : int或float,默认为0,标签的旋转角度(以度为单位)相对于屏幕坐标系。 grid : 布尔值,默认为True,将此设置为True将显示网格。 figsize : 以英寸为单位的元组(宽度,高度),在matplotlib中创建的图形的大小。 layout : 元组(行,列),可选,例如,(3,5)将从左上角开始使用3列和5行显示子图。 return_type : {‘axes’,‘dict’,‘both’}或None,默认’axes’要返回的那种对象。默认是axes。
'axes'返回绘制boxplot的matplotlib轴。
'dict'返回一个字典,其值是boxplot的matplotlib行。
'both'返回一个带有轴和dict的namedtuple。
分组时by,return_type返回一系列映射列 。
layout如果return_type为None,则返回具有相同形状的NumPy轴阵列。 ** kwds要传递给所有其他绘图关键字参数 matplotlib.pyplot.boxplot()、
df. plot( kind= 'box' ) ;
df. plot. box( ylabel= '销售额(万元)' ) ;
df. boxplot( ) ;
3.7.9 直方图
直方图是数值数据分布的精确图形表示,这是一个连续变量(定量变量)的概率分布的估计。
作用:
整理统计数据,了解统计数据的分布特征,即数据分布的集中或离散状况,从中掌握质量能力状态。 观察分析生产过程质量是否处于正常、稳定和受控状态以及质量水平是否保持在公差允许的范围内。
DataFrame. hist( data,
column= None ,
by= None ,
grid= True ,
xlabelsize= None ,
xrot= None ,
ylabelsize= None ,
yrot= None , ax= None ,
sharex= False ,
sharey= False ,
figsize= None ,
layout= None ,
bins= 10 ,
** kwds)
test_dict2 = { '泊松分布' : np. random. poisson( 50 , 100 ) , '贝塔分布' : np. random. beta( 5 , 1 , 100 ) * 40 }
df2 = pd. DataFrame( test_dict2)
df2
df2. hist( figsize= ( 10 , 5 ) , bins= 20 ) ;
3.7.10 核密度分布
核密度估计(kernel density estimation,KDE)是根据已知的一列数据(x1,x2,…xn)估计其密度函数的过程,即寻找这些数的概率分布曲线。 画频率直方图就是一种密度估计的方法,这里的“密度”(density)可以感性得理解为一个区间(直方图的组距)内数据数量的多少,右图即为这6个数据的密度曲线(这里简称为密度图),它是左图的外轮廓化,数据量越多,直方图的顶点也越接近一条线。 直方图和密度图都是一组数据在坐标轴上“疏密程度”的可视化,只不过直方图用条形图显示,而密度图使用拟合后的(平滑)的曲线显示,“峰”越高,表示此处数据越“密集”。“密度”越高,如下图。
df2. hist( bins= 20 )
df2. plot. kde( subplots= True )
df2. plot. density( subplots= True ) ;