python 数据分析 day4 pandas 之 Series


Python 数据分析day_1:认识Notebook,及NumPy , Pandas 和 Matplotlib基本使用方法
python 数据分析 day2 数组的运算及矩阵
python 数据分析 day3 矩阵及利用线性回归处理boston数据集
python 数据分析 day4 pandas 之 Series
python 数据分析day4 Pandas 之 DataFrame

pandas基础

导入常用库与基础设置

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

%config InlineBackend.figure_format = 'svg'

Pandas基本介绍

1.Series —> 数据系列 —> 代表一维数据,比ndarray的一维数组更加强大。

2.DataFrame —> 数据框/数据窗/数据表 —> 代表二维数据,数据可以是异质的。

3.Index —> 索引 —> 为Series和DataFrame提供了检索数据的方式。

Series

创建Series对象

创建Series对象的方法一:

ser1=pd.Series(data=[400,320,580,700],index=[f'{x}季度' for x in '1234'])
ser1

创建Series对象的方法二:

ser2=pd.Series(data={
    '1季度':400,
    '2季度':320,
    '3季度':580,
    '4季度':700
})
ser2

output:

1季度    400
2季度    320
3季度    580
4季度    700
dtype: int64

索引和切片

基本索引:

ser1[0],ser1['1季度'] #(400, 400)

ser1[-1],ser1['4季度'] #(700, 700)

布尔索引:

ser1[(ser1>500)|(ser1<400)]

"""
2季度    320
3季度    580
4季度    700
dtype: int64
"""

花式索引:

ser1[['1季度','3季度']]

"""
1季度    400
3季度    580
dtype: int64
"""

切片:

ser1[1:3]

"""
2季度    320
3季度    580
dtype: int64
"""
ser1['2季度':'3季度']
"""
2季度    320
3季度    580
dtype: int64
"""

Series对象的属性

获取数据系列的索引

ser1.index # Index(['1季度', '2季度', '3季度', '4季度'], dtype='object')

获取数据系列的值

ser1.values # array([400, 320, 580, 700], dtype=int64)

Not a Number —> 空值

ser1['2季度']=np.nan
ser1

"""
1季度    400.0
2季度      NaN
3季度    580.0
4季度    700.0
dtype: float64
"""

判断有没有空值

ser1.hasnans #True

赋值

ser1['2季度']=580
ser1

"""
1季度    400.0
2季度    580.0
3季度    580.0
4季度    700.0
dtype: float64
"""

判断是否单调递增

ser1.is_monotonic_increasing #False

判断数据是否唯一

ser1.is_unique #False

使用at(单元格索引,多用于DataFrame索引单元格)索引方式赋值

ser1.at['3季度']=600
ser1

"""
1季度    400.0
2季度    580.0
3季度    600.0
4季度    700.0
dtype: float64
"""

Series对象的方法

和统计相关的方法

print(ser1.max())
print(ser1.min())
print(ser1.sum())
print(ser1.mean())
print(ser1.std())
print(ser1.var())
print(ser1.count())
print(ser1.median())
# x%分位数
# 25%分位数就是下四分位数
print(ser1.quantile(0.25))
# 50%分位数就是中位数
print(ser1.quantile(0.5))
print(ser1.quantile(0.75))
print(ser1.quantile(0.9))
"""
700.0
400.0
2280.0
570.0
124.89995996796796
15600.0
4
590.0
535.0
590.0
625.0
670.0
"""

也可以通过numpy封装的方法获取统计信息

print(np.max(ser1)) #700.0
print(np.median(ser1)) #590.0

获取描述性统计信息

ser1.describe()

"""
count      4.00000
mean     570.00000
std      124.89996
min      400.00000
25%      535.00000
50%      590.00000
75%      625.00000
max      700.00000
dtype: float64
"""

ser4

ser4=pd.Series(data=['apple','waxberry','apple','apple','banana','waxberry'])
ser4

"""
0       apple
1    waxberry
2       apple
3       apple
4      banana
5    waxberry
dtype: object
"""

去重

ser4.unique() # array(['apple', 'waxberry', 'banana'], dtype=object)

统计每个值重复的次数(从高到低排列)

ser4.value_counts() 

"""
apple       3
waxberry    2
banana      1
dtype: int64
"""

ser5

ser5 = pd.Series(data=[120, np.nan, 350, 90, 170, np.nan, 300])
ser5
"""
0    120.0
1      NaN
2    350.0
3     90.0
4    170.0
5      NaN
6    300.0
dtype: float64
"""

统计方法会自动忽略掉空值

print(ser5.sum()) # 1030.0
print(ser5.count()) # 5

删除空值 - inplace参数表示是否就地删除

inplace=True(就地删除) - 直接在原对象上进行操作,不返回新对象
inplace=False(默认值) - 不修改原对象,返回修改后的新对象

ser5.dropna()

"""
0    120.0
2    350.0
3     90.0
4    170.0
6    300.0
dtype: float64
"""

填充空值

ser5.fillna(200)
"""
0    120.0
1    200.0
2    350.0
3     90.0
4    170.0
5    200.0
6    300.0
dtype: float64
"""
# 使填充值的值等于前一个值,前边没有值则该值为空
ser5.fillna(method='ffill') 
"""
0    120.0
1    120.0
2    350.0
3     90.0
4    170.0
5    170.0
6    300.0
dtype: float64
"""
# 使填充值的值等于后一个值,后边没有值则该值为空
ser5.fillna(method='bfill')
"""
0    120.0
1    350.0
2    350.0
3     90.0
4    170.0
5    300.0
6    300.0
dtype: float64
"""

数据筛选

ser5 = ser5.fillna(200)
ser5

0    120.0
1    200.0
2    350.0
3     90.0
4    170.0
5    200.0
6    300.0
dtype: float64
# where :符合条件的原样输出,其它置为0
ser5.where(ser5>150,0)

"""
0      0.0
1    200.0
2    350.0
3      0.0
4    170.0
5    200.0
6    300.0
dtype: float64
"""
# mask:符合条件的置零,其它的不变
ser5.mask(ser5>150,0)
"""
0    120.0
1      0.0
2      0.0
3     90.0
4      0.0
5      0.0
6      0.0
dtype: float64
"""
# 只保留符合条件的
ser5[ser5 > 150]
"""
1    200.0
2    350.0
4    170.0
5    200.0
6    300.0
dtype: float64
"""

计算众数:(众数可能有多个数,所以返回的不是一个值而是一个数据系列)

ser6 = pd.Series(data=[1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 5])
ser6.mode()
"""
0    3
dtype: int64
"""
ser6.mode()[0] # 3

数据映射和转换

ser7 = pd.Series(['cat', 'dog', np.nan, 'rabbit'])
ser7

"""
0       cat
1       dog
2       NaN
3    rabbit
dtype: object
"""


ser7.map('I am a {}'.format,na_action='ignore')
"""
0       I am a cat
1       I am a dog
2              NaN
3    I am a rabbit
dtype: object
"""
ser8 = pd.Series(data=[1, 2, np.nan, 4])
ser8.map(np.sqrt,na_action='ignore')

"""
0    1.000000
1    1.414214
2         NaN
3    2.000000
dtype: float64
"""

*补充:数据归一化处理(重要)

补充:数据归一化处理 —> 避免值很大的特征对整个运算的结果产生压倒式的影响。

线性归一化(标准化):

X i ∗ = X i − X m i n X m a x − X m i n X_i^* = \frac {X_i - X_{min}} {X_{max} - X_{min}} Xi=XmaxXminXiXmin

零均值归一化(中心化):

X i ∗ = X i − μ σ X_i^* = \frac {X_i - \mu} {\sigma} Xi=σXiμ

ser1

1季度    400.0
2季度    580.0
3季度    600.0
4季度    700.0
dtype: float64

线性归一化(标准化)

x_min, x_max = ser1.min(), ser1.max()
ser1.apply(lambda x:round((x-x_min)/(x_max-x_min),4))

"""
1季度    0.0000
2季度    0.6000
3季度    0.6667
4季度    1.0000
dtype: float64
"""

零均值归一化(中心化)

mu,sigma=ser1.mean(),ser1.std()
ser1.apply(lambda x:round((x - mu) / sigma, 4))
"""
1季度   -1.3611
2季度    0.0801
3季度    0.2402
4季度    1.0408
dtype: float64
"""

根据Series对象的值排序(ascending参数控制升序还是降序,默认是升序)

ser1.sort_values(ascending=False)

"""
4季度    700.0
3季度    600.0
2季度    580.0
1季度    400.0
dtype: float64
"""

根据Series对象的索引排序

ser1.sort_index(ascending=False)

"""
4季度    700.0
3季度    600.0
2季度    580.0
1季度    400.0
dtype: float64
"""
ser9 = pd.Series(
    data=[35, 96, 12, 57, 25, 89], 
    index=['grape', 'banana', 'pitaya', 'apple', 'peach', 'orange']
)
# 按值排序从小到大排序
ser9.sort_values()

"""
pitaya    12
peach     25
grape     35
apple     57
orange    89
banana    96
dtype: int64
"""

# 按索引从大到小排序
ser9.sort_index(ascending=False)

"""
pitaya    12
peach     25
orange    89
grape     35
banana    96
apple     57
dtype: int64
"""

值最大的3个

ser9.nlargest(3)

"""
banana    96
orange    89
apple     57
dtype: int64
"""

值最小的2个

ser9.nsmallest(2)
"""
pitaya    12
peach     25
dtype: int64
"""

在Series对象上出图

看趋势–>折线图

# 在Series对象上出图
# 看趋势 --> 折线图
ser1.plot(kind='line', color='red')
# 设置横纵坐标的标签
plt.xlabel('季度')
plt.ylabel('销售额(万元)')
# 设置图的标题
plt.title('千锋互联成都分公司销售额')
# 设置网格线
plt.grid(axis='y', linestyle='--')
# 设置横纵坐标的刻度
plt.xticks(np.arange(4), labels=ser1.index)
plt.yticks(np.arange(300, 801, 100))
# 保存统计图
plt.savefig('sales-2020.png')
# 显示统计图
plt.show()

在这里插入图片描述
看差距 --> 柱状图

ser1.plot(kind='bar', color=['red', '#00ff00', 'blue', '#c0c0c0'])
plt.xticks(rotation=30)
plt.grid(axis='y', linestyle='--', alpha=0.3)
for i in range(4):
    plt.text(i, ser1[i] + 5, ser1[i], ha='center')
plt.show()

在这里插入图片描述
看占比 --> 饼图

ser1.plot(kind='pie', autopct='%.1f%%', explode=[0, 0, 0.1, 0], shadow=True)
plt.ylabel('')
plt.show()

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值