Pandas
1.Pandas介绍
pandas 是基于 Numpy 构建的含有更高级数据结构和工具的数据分析包类似于 Numpy 的核心是 ndarray,pandas 也是围绕着 Series 和 DataFrame 两个核心数据结构展开的 。Series 和 DataFrame 分别对应于一维的序列和二维的表结构。通俗点讲,Pandas就是带有标签的Numpy。
导包语法:from pandas import Series,DataFrame
import pandas as pd
2.Series
Series就是一维数组,但是与Numpy中的array相比,前者不仅有数据,有对应的标签或者说是索引。
import pandas as pd
a = pd.Series([1.1,1.2,1.3,1.4])
print(a)
print("----")
b = pd.Series(data=[1,3,5,'abc'],index=['no.1','no.2','no.3','no.4'])
print(b)
print("----")
print(a.values)
print("----")
print(b.index)
print("----")
print(b['no.2'])
print("----")
print(b[['no.1','no.3','no.4']])
-----------------------------------
0 1.1
1 1.2
2 1.3
3 1.4
dtype: float64
----
no.1 1
no.2 3
no.3 5
no.4 abc
dtype: object
----
[1.1 1.2 1.3 1.4]
----
Index(['no.1', 'no.2', 'no.3', 'no.4'], dtype='object')
----
3
----
no.1 1
no.3 5
no.4 abc
dtype: object
这上面这个例子可以知道,series存储的数据类型可以不一致,,也可以对series中的某一部分通过这部分的索引截取出来。
python中的字典可以直接转换成series,见下面的代码。
dic = {"name":"小米","age":8,"sex":"female"}
dic_series = pd.Series(dic)
print(dic_series)
------------------------------
name 小米
age 8
sex female
dtype: object
同种类型的series在进行运算的时候可以自动按照索引对齐进行计算。
score1 = pd.Series(data=[55,66,77],index=['math','chinese','english'])
score2 = pd.Series(data=[55,66,77],index=['chinese','math','english'])
print(score1+score2)
----------------------------
chinese 121
english 154
math 121
dtype: int64
可以根据索引来改变值,也可以改变索引。
score1 = pd.Series(data=[55,66,77],index=['math','chinese','english'])
score2 = pd.Series(data=[55,66,77],index=['chinese','math','english'])
score1['math'] = 99
print(score1)
score2.index=['001','002','003']
print(score2)
---------------------------
math 99
chinese 66
english 77
dtype: int64
001 55
002 66
003 77
dtype: int64
3.DataFrame