Python库-pandas详解
1. pandas介绍
pandas 是用于数据挖掘的Python库
- 便捷的数据处理能力
- 独特的数据结构
- 读取文件方便
- 封装了matplotlib的画图和numpy的计算
pandas的数据结构
- Series
- Series 类似表格中的一个列(column),类似于一维数组,可以保存任何数据类型。由索引(index)和列组成。
- DataFrame
- DataFrame 是一个表格型的数据结构,每列可以是不同的值类型(数值、字符串、布尔型值)。DataFrame 既有行索引也有列索引,它可以被看做由 Series 组成的字典。
案例应用
创建一个符合正态分布的10个股票5天的涨跌幅数据,使用pandas中的数据结构 DataFrame() 处理数据
# 导入库
import numpy as np
import pandas as pd
# 创建一个符合正态分布的10个股票5天的涨跌幅数据
stocks = np.random.normal(0, 1, [10, 5])
# 使用pandas中的数据结构 DataFrame() 处理数据
stocks_rise = pd.DataFrame(stocks)
# 设置行索引,获取行数 stocks_rise.shape[0] 进行遍历 列表生成式
index_row = ['股票{}'.format(i+1) for i in range(stocks_rise.shape[0])]
# 设置列索引,日期是一个时间序列,为了简便,使用pd.date_range()生成一组连续的时间序列
# pd.date_range(start,end,periods,freq) start:开始时间, end:结束时间
# periods:时间天数, freq:递进单位,默认1天,'B'默认略过周末
index_col = pd.date_range(start='20220201',periods=stocks_rise.shape[1],freq='B')
# 添加索引,注意数据是ndarray数据 index表示行索引,columns表示列索引
data = pd.DataFrame(stocks, index=index_row, columns=index_col)
print(data)
2022-02-01 2022-02-02 2022-02-03 2022-02-04 2022-02-07
股票1 -2.054041 -1.170757 0.162393 0.253333 -1.638837
股票2 -1.463734 0.408459 0.530070 -0.925281 1.454630
股票3 -0.511517 -0.827591 -2.076265 0.139486 0.658707
股票4 -1.698789 0.250902 -0.624713 1.378845 -1.672292
股票5 0.683233 -1.083694 0.810567 0.421215 1.375385
股票6 -0.296111 -0.946959 0.836536 -1.179879 -0.397406
股票7 0.017772 0.180210 2.022776 0.436337 -1.555866
股票8 0.638262 -0.790932 1.077822 -1.746631 -0.591360
股票9 -0.681391 -0.613255 -1.849094 0.438304 -0.503742
股票10 -0.243500 -1.733623 -1.137840 0.124976 -0.415727
2. Series
pd.Series( data, index, dtype, name, copy)
参数说明:
data:一组数据(ndarray 类型)。
index:数据索引标签,如果不指定,默认从 0 开始。
dtype:数据类型,默认会自己判断。
name:设置名称。
copy:拷贝数据,默认为 False。
Series实例
# 通过数组创建Series
s = pd.Series([6, 5, 2], index=['x', 'y', 'z'])
print(s)
x 6
y 5
z 2
# 通过字典创建Series
s = pd.Series({
'day': 2,
'month': 2,
'year': 2022
})
print(s)
day 2
month 2
year 2022
dtype: int64
# 通过索引操作数据
print(s['year'])
2022
3. DataFrame
3.1 DataFrame结构
DataFrame对象既有行索引,又有列索引
- 行索引:表明不同行,横向索引,叫index,axis=0
- 列索引:表明不同列,纵向索引,叫columns,axis=1
3.2 DataFrame属性与方法
-
shape DataFrame的形状
-
index DataFrame行索引
-
columns DataFrame列索引
-
values DataFrame的值
-
T DataFrame转置
-
head(n) DataFrame的前n行,默认为前5行
-
tail(n) DataFrame的后n行,默认为后5行
print(data.shape) # (10, 5)
print(data.index)Index([‘股票1’, ‘股票2’, ‘股票3’, ‘股票4’, ‘股票5’, ‘股票6’, ‘股票7’, ‘股票8’, ‘股票9’, ‘股票10’], dtype=‘object’)
print(data.columns)