文章目录
0. 序
Pandas 官方网站简介:
pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool,
built on top of the Python programming language.
—https://pandas.pydata.org/
也有人建议可以讲Pandas理解成一个增强型的Excel。我觉得吧,天下武功,不练不成功。废话不多说,开始絮叨。
1. Series 序列
窃以为Pandas的核心在于Series,至于为何这么说,客官可以听我慢慢道来。
1.1 什么式Series
Pandas 的Series 与Numpy的数组有点像 (貌似Series本来就是简历在Numpy 数组对象的基础上的),但是Series与南派数组相比,有以下特征:
- Series 有轴标 (行头 或 列头 标识字符串)
- 可以用轴标来进行索引 (亦可以用数字坐标索引)
- 元素不仅仅可以存数据,还可以是任何python对象
1.2 生成Series
不管懂不懂这个东西,程咬金的三板斧要先劈出来,乍一看,还挺专业:
import numpy as np
import pandas as pd
可以通过转换 python串串,南派数组 或者 字典 来生成序列
my_labels = ['a','b','c']
my_list = [100,200,300]
my_array = np.array([10,20,30])
my_dict = {'a':10,'b':20,'c':30}
pd.Series(data=my_list)
0 100
1 200
2 300
dtype: int64
pd.Series(data=my_list,index=my_labels)
# or
pd.Series(my_list,my_labels)
a 100
b 200
c 300
dtype: int64
pd.Series(my_array)
0 10
1 20
2 30
dtype: int32
pd.Series(my_array,my_labels)
a 10
b 20
c 30
dtype: int32
pd.Series(my_dict)
a 10
b 20
c 30
dtype: int64
pd.Series(data=my_labels)
0 a
1 b
2 c
dtype: object
1.3 坐标索引 与 序列相加
ser1 = pd.Series(my_list,my_labels)
ser2 = pd.Series(my_list,['a','c','e'])
ser1:
a 100
b 200
c 300
ser2:
a 100
c 200
e 300
ser1['b']
200
ser1 + ser2
a 200.0
b NaN
c 500.0
e NaN
dtype: float64