第3章 Pandas基础

目录

本文的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 用列表创建
  • index缺省,默认为整数序列
import pandas as pd                          # 导入pandas库
# 根据列表创建Series类对象
ser_obj = pd.Series(['Python', 'Java', 'PHP'])   
ser_obj
0    Python
1      Java
2       PHP
dtype: object
  • 增加index
# 导入pandas库
import pandas as pd                          
# 创建Series类对象,同时为该对象指定索引
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 用字典创建
  • 默认以键为index,值为data
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)
# 创建Series类对象,指定索引为时间戳索引
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
BeiJing2154
ShangHai2424
ShenZhen1303
HangZhou981
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})
populationGDP
BeiJing215430320
ShangHai242432680
ShenZhen130324222
HangZhou98113468

若行索引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})
populationGDP
BeiJing2154.030320
ChongqingNaN10000
HangZhou981.013468
ShangHai2424.032680
ShenZhen1303.024222

注意:标量时会自动补齐

pd.DataFrame({"population": population,
              "GDP": GDP,
              "country": "China"})
populationGDPcountry
BeiJing215430320China
ShangHai242432680China
ShenZhen130324222China
HangZhou98113468China
3.1.2.3 通过字典列表对象创建
  • 字典索引作为index,字典键作为columns
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
ab
000
112
224
  • 不存在的键,会默认值为NaN
data = [{"a": 1, "b":1},{"b": 3, "c":4}]
pd.DataFrame(data)
abc
01.01NaN
1NaN34.0
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)       # 根据二维数组创建DataFrame类对象
df_obj
012
0abc
1def
# 创建DataFrame类对象,同时指定行索引与列索引
df_obj = pd.DataFrame(demo_arr, index = ['row_01','row_02'],
                          columns=['col_01', 'col_02', 'col_03'])
df_obj
col_01col_02col_03
row_01abc
row_02def

3.2 DataFrame属性

data = pd.DataFrame({"population": population,
              "GDP": GDP})
data
populationGDP
BeiJing215430320
ShangHai242432680
ShenZhen130324222
HangZhou98113468

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 # = data.shape[0]*data.shape[1]
8

3.2.6 .dtypes 返回每列数据类型

data.dtypes
population    int64
GDP           int64
dtype: object

3.3 索引操作

3.3.1 索引对象

data
populationGDP
BeiJing215430320
ShangHai242432680
ShenZhen130324222
HangZhou98113468
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
BeiJing30320
ShangHai32680
ShenZhen24222
HangZhou13468
type(data[['GDP']])
pandas.core.frame.DataFrame
# 获取多列  ,注意是双中括号
data[['GDP','population']]
GDPpopulation
BeiJing303202154
ShangHai326802424
ShenZhen242221303
HangZhou13468981
  • 对象属性式
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
populationGDP
BeiJing215430320
ShangHai242432680
ShenZhen130324222
HangZhou98113468
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
populationGDP
BeiJing215430320
ShangHai242432680
ShenZhen130324222
HangZhou98113468
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
populationGDP
BeiJing215430320
ShangHai242432680
ShenZhen130324222
HangZhou98113468
  • .loc[行索引名称,列索引名称]方式
data.loc['BeiJing','GDP']
30320
  • .loc[行索引名称][列索引名称]方式
data.loc['BeiJing']['GDP']
30320
# 本质是先获取series,在用series取值的方式
data.loc["BeiJing"]
population     2154
GDP           30320
Name: BeiJing, dtype: int64
  • .iloc[行索引值,列索引值]方式
data.iloc[0,1]
30320
  • .iloc[行索引值][列索引值]方式
data.iloc[0][1]
30320
  • .at[行索引名称,列索引名称]方式
data.at["BeiJing",'GDP']
30320
  • .iat[行索引值,列索引值]方式
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
ABCD
2019-01-01-0.631020-0.6219690.8109360.631151
2019-01-02-0.6930421.8453780.6174470.282174
2019-01-03-0.4690420.4487701.309556-0.872601
2019-01-04-0.0708321.2185910.3523820.283966
2019-01-050.1326111.828863-1.0355170.491823
2019-01-060.892035-1.230534-1.454877-0.237451
3.3.2.1 行切片
df["2019-01-01": "2019-01-03"]
ABCD
2019-01-01-0.631020-0.6219690.8109360.631151
2019-01-02-0.6930421.8453780.6174470.282174
2019-01-03-0.4690420.4487701.309556-0.872601
df["2019-01-01": "2019-01-05":2]
ABCD
2019-01-01-0.631020-0.6219690.8109360.631151
2019-01-03-0.4690420.4487701.309556-0.872601
2019-01-050.1326111.828863-1.0355170.491823
df.loc["2019-01-01": "2019-01-03"]
ABCD
2019-01-01-0.631020-0.6219690.8109360.631151
2019-01-02-0.6930421.8453780.6174470.282174
2019-01-03-0.4690420.4487701.309556-0.872601
# .iloc[起始索引值:终止索引值]
df.iloc[0: 3]
ABCD
2019-01-01-0.631020-0.6219690.8109360.631151
2019-01-02-0.6930421.8453780.6174470.282174
2019-01-03-0.4690420.4487701.309556-0.872601
# .iloc[起始索引值:终止索引值:步长]
df.iloc[0: 5: 2]
ABCD
2019-01-01-0.631020-0.6219690.8109360.631151
2019-01-03-0.4690420.4487701.309556-0.872601
2019-01-050.1326111.828863-1.0355170.491823
3.3.2.2 列切片
df
ABCD
2019-01-01-0.631020-0.6219690.8109360.631151
2019-01-02-0.6930421.8453780.6174470.282174
2019-01-03-0.4690420.4487701.309556-0.872601
2019-01-04-0.0708321.2185910.3523820.283966
2019-01-050.1326111.828863-1.0355170.491823
2019-01-060.892035-1.230534-1.454877-0.237451
df.loc[:,"A":"C"]
ABC
2019-01-01-0.631020-0.6219690.810936
2019-01-02-0.6930421.8453780.617447
2019-01-03-0.4690420.4487701.309556
2019-01-04-0.0708321.2185910.352382
2019-01-050.1326111.828863-1.035517
2019-01-060.892035-1.230534-1.454877
df.loc[:,"A":"C":2]
AC
2019-01-01-0.6310200.810936
2019-01-02-0.6930420.617447
2019-01-03-0.4690421.309556
2019-01-04-0.0708320.352382
2019-01-050.132611-1.035517
2019-01-060.892035-1.454877
df.iloc[:,0:3:2]
AC
2019-01-01-0.6310200.810936
2019-01-02-0.6930420.617447
2019-01-03-0.4690421.309556
2019-01-04-0.0708320.352382
2019-01-050.132611-1.035517
2019-01-060.892035-1.454877
3.3.2.3 花式切片
  • 行、列同时切片
df.loc["2019-01-02": "2019-01-03", "C":"D"]
CD
2019-01-020.6174470.282174
2019-01-031.309556-0.872601
df.iloc[1: 3, 2:]
CD
2019-01-020.6174470.282174
2019-01-031.309556-0.872601
  • 行切片,列分散取值
df.loc["2019-01-04": "2019-01-06", ["A", "C"]]
AC
2019-01-04-0.0708320.352382
2019-01-050.132611-1.035517
2019-01-060.892035-1.454877
df.iloc[3:, [0, 2]]
AC
2019-01-04-0.0708320.352382
2019-01-050.132611-1.035517
2019-01-060.892035-1.454877
  • 行分散取值,列切片
df.loc[["2019-01-02", "2019-01-06"], "C": "D"]
CD
2019-01-020.6174470.282174
2019-01-06-1.454877-0.237451
  • 行、列均分散取值
df.loc[["2019-01-04", "2019-01-06"], ["A", "D"]]
AD
2019-01-04-0.0708320.283966
2019-01-060.892035-0.237451
df.iloc[[1, 5], [0, 3]]
AD
2019-01-02-0.6930420.282174
2019-01-060.892035-0.237451

3.3.3 布尔索引

df
ABCD
2019-01-01-0.631020-0.6219690.8109360.631151
2019-01-02-0.6930421.8453780.6174470.282174
2019-01-03-0.4690420.4487701.309556-0.872601
2019-01-04-0.0708321.2185910.3523820.283966
2019-01-050.1326111.828863-1.0355170.491823
2019-01-060.892035-1.230534-1.454877-0.237451
# 找出大于0的值
df>0
ABCD
2019-01-01FalseFalseTrueTrue
2019-01-02FalseTrueTrueTrue
2019-01-03FalseTrueTrueFalse
2019-01-04FalseTrueTrueTrue
2019-01-05TrueTrueFalseTrue
2019-01-06TrueFalseFalseFalse
df[df > 0]
ABCD
2019-01-01NaNNaN0.8109360.631151
2019-01-02NaN1.8453780.6174470.282174
2019-01-03NaN0.4487701.309556NaN
2019-01-04NaN1.2185910.3523820.283966
2019-01-050.1326111.828863NaN0.491823
2019-01-060.892035NaNNaNNaN
#找出A列值大于0的行
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]
ABCD
2019-01-050.1326111.828863-1.0355170.491823
2019-01-060.892035-1.230534-1.454877-0.237451
  • isin()方法
df2 = df.copy()
df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three']
df2
ABCDE
2019-01-01-0.631020-0.6219690.8109360.631151one
2019-01-02-0.6930421.8453780.6174470.282174one
2019-01-03-0.4690420.4487701.309556-0.872601two
2019-01-04-0.0708321.2185910.3523820.283966three
2019-01-050.1326111.828863-1.0355170.491823four
2019-01-060.892035-1.230534-1.454877-0.237451three
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"])]
ABCDE
2019-01-03-0.4690420.4487701.309556-0.872601two
2019-01-050.1326111.828863-1.0355170.491823four

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
cacb
0122
ra0ABCD
1EFGH
rb2IJKL
2MNOP
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)
0123
numbercolor
1redABCD
blueEFGH
2redIJKL
blueMNOP
 df = pd.DataFrame([['HI', 'Temp'], ['HI', 'Precip'],
...                    ['NJ', 'Temp'], ['NJ', 'Precip']],
...                   columns=['a', 'b'])
df
ab
0HITemp
1HIPrecip
2NJTemp
3NJPrecip
  • 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)
0123
ab
HITempABCD
PrecipEFGH
NJTempIJKL
PrecipMNOP
  • 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'])
# print(df)
df
JavaWebPython
张三期中202756
期末822186
李四期中01123
期末581926
王五期中887676
期末982931

3.3.4.2 使用分层索引访问数据
  • Series的分层索引
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
  • dataframe的分层索引
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"]
GreenRed
a101
234
b167
2910
frame["A"]["Green"]
a  1    0
   2    3
b  1    6
   2    9
Name: Green, dtype: int32
frame["B"]
Green
a12
25
b18
211
# 访问第一层索引为'A'的数据
print(frame['A'])
     Green  Red
a 1      0    1
  2      3    4
b 1      6    7
  2      9   10
# 访问'A'嵌套的索引为'Green'的数据
print(frame['A']['Green'])
a  1    0
   2    3
b  1    6
   2    9
Name: Green, dtype: int32
frame
AB
GreenRedGreen
a1012
2345
b1678
291011
frame.loc["a","A"]
GreenRed
101
234
frame.loc["a"]["A"]
GreenRed
101
234
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"]
AB
GreenRedGreen
1012
2345
# 访问列索引标签为a的数据,第一层索引
print(frame.loc['a'])
      A         B
  Green Red Green
1     0   1     2
2     3   4     5
# 访问列索引标签为A的数据,第二层索引
print(frame.loc['a', 'A'])
   Green  Red
1      0    1
2      3    4
frame
AB
GreenRedGreen
a1012
2345
b1678
291011
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
#reindex用法示例
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
#使用ffill实现前向值填充
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
# 通过fill_value参数,使用指定值对缺失值进行填充
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
abcd
A10443985
B54774140
C5133688
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
abcd
A100443985
B54774140
C5133688
df2 = df.loc["A":"B","a":"c"]
print(type(df2))
df2
<class 'pandas.core.frame.DataFrame'>
abc
A1004439
B5477741
df2.loc["B","b"] = 888
df2
abc
A1004439
B5488841
df
abcd
A100443985
B548884140
C5133688
# 利用.copy()得到副本
df22 = df.loc["A":"B","a":"c"].copy()
print(type(df22))
df22
<class 'pandas.core.frame.DataFrame'>
abc
A1004439
B5488841
df22.loc["A","b"]=444
df22
abc
A10044439
B5488841
df
abcd
A100443985
B548884140
C5133688

3.3.6.2 花式索引得到的是副本
df31 = df.loc[["A","C"],"a":"c"]
df31
abc
A1004439
C51336
df31.loc["C","b"] = 333
df31
abc
A1004439
C5133336
df31
abc
A1004439
C5133336
df
abcd
A100443985
B548884140
C5133688
df3 = df.loc[["A","C"],["a","c"]]
print(type(df3))
df3
<class 'pandas.core.frame.DataFrame'>
ac
A10039
C5136
df3.iloc[1,1] = 999
df3
ac
A10039
C51999
df
abcd
A100443985
B548884140
C5133688

3.4 数据处理常用的操作:增、删、查、改

3.4.1 增

3.4.1.1 增加行
  • 插入数据行
#创建一个数据框
arr = np.arange(9)
ar = arr.reshape(3,3)
df = pd.DataFrame(ar)
df
012
0012
1345
2678
##【插入数据行】
df.loc[6]=['a','b','c']     #指定的位置插入一行,行的索引名必须是不存在的,且长度同现有的行数据长度
df
012
0012
1345
2678
6abc
  • 合并数据框
df0 = pd.DataFrame([6,6,6]).T #创建一个新数据框
df0
012
0666
pd.concat([df,df0],ignore_index=False)  #将df0合并到df中并生成新的数据框,ignore_index=True表示新的数据框的索引被默认改变顺延
012
0012
1345
2678
6abc
0666
pd.concat([df,df0],ignore_index=True)  #将df0合并到df中并生成新的数据框,ignore_index=True表示新的数据框的索引被默认改变顺延
012
0012
1345
2678
3abc
4666
# concat后的结果是副本非原有两个df的视图
df1 = pd.concat([df,df0],ignore_index=True)  #将df0合并到df中并生成新的数据框,ignore_index=True表示新的数据框的索引被默认改变顺延
df1
012
0012
1345
2678
3abc
4666
df0.iloc[0,1]=666
df0
012
066666
df1
012
0012
1345
2678
3abc
4666
3.4.1.2 增加列

增加一列很简单,类似于字典,若存在则覆盖,没有则新增一列,前提是该列与已有的列长度相等。

df 
012
0012
1345
2678
6abc
df['new'] = ['a','b','c','d']#插入列
df
012new
0012a
1345b
2678c
6abcd
df.insert(2,'colunm_b',[4,0,2,1])    #在指定的位置插入一列
df
01colunm_b2new
00142a
13405b
26728c
6ab1cd

3.4.2 删

3.4.2.1 删除列
df
01colunm_b2new
00142a
13405b
26728c
6ab1cd
####【删除1列】
df.drop('colunm_b' ,axis=1, inplace = True) #删除列,inplace = True表示在原数据上
df
012new
0012a
1345b
2678c
6abcd
#删除多列
df.drop(df.columns[[0,1]], axis=1,inplace= False)   
2new
02a
15b
28c
6cd
df
012new
0012a
1345b
2678c
6abcd
3.4.2.2 删除行
df.drop(1, axis=0, inplace = False)   #按照索引号/名删除行时 axis=0可省略,inplace = False时也可以省略
012new
0012a
2678c
6abcd
df 
#按照索引号删除
df.drop(df.index[3], inplace = True)  
df
012new
0012a
1345b
2678c
#删除多个行
df.drop(df.index[[1,2]], inplace = False)  
012new
0012a
  • 删除特定数值的行,其实是筛选
df
012new
0012a
1345b
2678c
df[~df['new'].str.contains('c')]    #删除列名为2的包含字母c的行
012new
0012a
1345b
df
012new
0012a
1345b
2678c
# 也可以如下操作布尔索引
df[df['new']!='c']
012new
0012a
1345b

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
abc
0100
1222
2311
3222
#查找a列数据为3的行
df[df['a']==3]
abc
2311
#也可以用where处理
np.where(df==3) #查找制定的元素或者值
(array([2], dtype=int64), array([0], dtype=int64))
df==3
abc
0FalseFalseFalse
1FalseFalseFalse
2TrueFalseFalse
3FalseFalseFalse
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
abc
0100.0
1222.0
231NaN
3222.0
np.where(np.isnan(df))  #但是查找空值Nan时最好用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
abc
0100.0
1222.0
231NaN
3222.0
df_0 = df.duplicated('a')  #显示各行是否重复, bool类型
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
abc
0100.0
1222.0
231NaN
3222.0
#也可以直接用删除行操作
df.drop(3, axis=0, inplace = False) 
abc
0100.0
1222.0
231NaN
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
abc
A11112
B22122
C33132
D44142
  • 更改某一个确切位置的值
df.loc["A","a"] = "11"
df
abc
A111112
B22122
C33132
D44142
  • 更改某列的值
df['a'] = ['1','2','3','4']
df
abc
A11112
B22122
C33132
D44142
  • 更改某行的值
df.loc['D'] = ["4",41,420]
df
abc
A11112
B22122
C33132
D441420
3.4.4.2 更改数据类型
# 如下操作会出错
df["a"]+df["b"]
df.info()  #课件第1行数据类型为object(str)
<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
abc
A11112
B22122
C33132
D441420
# 更改行索引名
df.index = [i for i in range(len(df))]
df
abc
011112
122122
233132
3441420
# 更改列索引名
df.columns = [i for i in range(df.shape[1])]
df
012
011112
122122
233132
3441420

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'])
# 显示创建的df对象
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
cab
B012
C345
A678
df
cab
A678
B012
C345
df.sort_index(inplace=True)
col_sort = df.sort_index(axis=1)
col_sort
abc
B120
C453
A786
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
AB
GreenRedGreen
a5012
2345
b3678
191011
df2.sort_index(level=1)
AB
GreenRedGreen
b191011
a2345
b3678
a5012

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_Acol_Bcol_C
054.06
11NaN3
244.08
362.00
new_df = df.sort_values(by='col_B')
new_df
col_Acol_Bcol_C
362.00
054.06
244.08
11NaN3
new_df2 = df.sort_values(by=['col_B','col_A'])
new_df2
col_Acol_Bcol_C
362.00
244.08
054.06
11NaN3
new_df3 = df.sort_values(by=['col_B','col_A'],ascending=[True, False])
new_df3
col_Acol_Bcol_C
362.00
054.06
244.08
11NaN3
df.sort_values(by='col_B', na_position='first')
col_Acol_Bcol_C
11NaN3
362.00
014.06
244.08

3.6 统计计算于统计描述

3.6.1 数据总览查看

  • DataFrame.head()
  • DataFrame.tail()
  • DataFrame.describe()
  • DataFrame.info()

# 构建一个dataframe  12个同学,5个科目成绩列表
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
pythoncjavamathEnglish
李思艺9676737765
刘昕7995958792
朱银莎6361738890
张德荣8794678584
张维涛9867616697
牟伦聪7778899574
谭汶江9662639163
唐周润6967947397
张淑琪6672878487
宋越9695977798
曾尧9373916391
李良鱼8371616080
3.6.1.1 查看前面的行 .head()
scoreOfClass1.head()#默认前5行
pythoncjavamathEnglish
李思艺9676737765
刘昕7995958792
朱银莎6361738890
张德荣8794678584
张维涛9867616697
scoreOfClass1.head(3) # 查看前3行
pythoncjavamathEnglish
李思艺9676737765
刘昕7995958792
朱银莎6361738890
3.6.1.2 查看后面的行.tail()
scoreOfClass1.tail()#默认最后5行
pythoncjavamathEnglish
唐周润6967947397
张淑琪6672878487
宋越9695977798
曾尧9373916391
李良鱼8371616080
scoreOfClass1.tail(3)  # 查看最后3行
pythoncjavamathEnglish
宋越9695977798
曾尧9373916391
李良鱼8371616080
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()
pythoncjavamathEnglish
count12.00000012.00000012.00000012.00000012.000000
mean83.58333375.91666779.25000078.83333384.833333
std12.72405312.36901114.24541411.42432312.066734
min63.00000061.00000061.00000060.00000063.000000
25%75.00000067.00000066.00000071.25000078.500000
50%85.00000072.50000080.00000080.50000088.500000
75%96.00000082.00000091.75000087.25000093.250000
max98.00000095.00000097.00000095.00000098.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
ABC
02.01.03
13.0NaN4
21.00.05
# 默认情况下迭代行并在每列中查找总和。这相当于axis=None或axis='index'
df.cumsum()
ABC
02.01.03
15.0NaN7
26.01.012
df
ABC
02.01.03
13.0NaN4
21.00.05
# 要迭代列并在每行中查找总和,请使用 axis=1
df.cumsum(axis=1)
ABC
02.03.06.0
13.0NaN7.0
21.01.06.0

cumprod()类似

df.cumprod()
ABC
02.01.03
16.0NaN12
26.00.060
df.cumprod(axis='columns')
ABC
02.02.06.0
13.0NaN12.0
21.00.00.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季度217
第2季度3435
第3季度25455
第4季度493
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']})   #这是方便seaborn绘图得时候得字体设置

# 重新绘制
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 垂直条形图
  • DataFrame.plot(kind=‘bar’)

  • DataFrame.plot.bar()

  • 普通条形图

df.plot(kind='bar');

在这里插入图片描述

df.plot.bar();

在这里插入图片描述

  • 堆积条形图
df.plot(kind='bar',stacked=True);

在这里插入图片描述

df.plot.bar(stacked=True);

在这里插入图片描述

  • 子图并调整x轴标签的旋装方向
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, # 百分比的text离圆心的距离
        explode = (0,0,0.1,0,0,0), # 将第3各数据抽取出来
        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
销售量收藏
一月10001500
二月20002300
三月50003500
四月20002400
五月40001900
六月30003000
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);

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值