Pandas介绍
Python Data Analysis Library即Pandas是基于NumPy 的一种Python数据分析工具包,包含丰富的数据类型和便捷的操作方式。
基本数据类型
Series
对应Python中的列表和NumPy的一维数组,Series可以指定索引内容,默认索引与Python相同从0开始的整形数
import pandas as pd
s = pd.Series([1,20,33,np.nan,5,66])
print(s)
output:
0 1.0
1 20.0
2 33.0
3 NaN
4 5.0
5 66.0
dtype: float64
可以使用自定义列表作为索引参数,例如时间序列
dates = pd.date_range('20180205',periods=6)
s = pd.Series([1,3,6,np.nan,44,1],index=dates)
print(s)
output:
2018-02-05 1.0
2018-02-06 20.0
2018-02-07 33.0
2018-02-08 NaN
2018-02-09 5.0
2018-02-10 66.0
Freq: D, dtype: float64
之后可以通过索引访问数据了
s['2018-2-07']
output:33.0
DataFrame
DataFrame提供表格类型的数据结构,相当于矩阵,NumPy里的二维数组和Python的字典。和Series同样的,DataFrame也有索引,包含行索引(index)和列索引(columns)。
DataFrame可以看做是由Series组成的大字典,二者关系类似于列向量和矩阵的关系。
默认索引与Series一致,均从0开始
df = pd.DataFrame(np.arange(12).reshape((3,4)))
print(df)
output:
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
指定含参索引如下
df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=['a','b','c','d'])
print(df)
output:
a b c d
2018-02-05 0.350842 0.316069 0.283373 -1.171848
2018-02-06 0.557246 -2.338000 0.743795 -0.332596
2018-02-07 -0.056014 0.714417 2.609023 0.825786
2018-02-08 -0.638557 1.815248 -0.898888 1.120689
2018-02-09 -1.113309 1.315297 -1.694181 0.274465
2018-02-10 -0.640387 -0.098660 -2.717680 -0.017176
可调用属性
dtype 查看每个列的数据类型
index 查看行索引及其数据类型
columns 查看列索引及其数据类型
values 以数组形式返回DataFrame的值(去索引)
describe 显示数据的总结信息(均值,方差等)
transpose DataFrame的转置
DataFrame类中定义了排序方法
df.sort_index(axis=0,ascending=False)
其中axis=0,代表按行排序,axis=1,代表按列排序
ascending=True代表正序,False代表逆序
还可以采用按值排序的方法
df.sort_values(by='E')
该方法按指定索引的值进行排序