Pandas概况:
Pandas是Python的核心数据分析支持库,提供了快速、灵活、明确的数据结构,
旨在简单、直观地处理关系型、标记型数据。Pandas是Python 数据分析实践与实战的必备高级工具。
Pandas 适用于处理以下类型的数据:
与SQL或Excel 表类似的,含异构列的表格数据;
有序和无序(非固定频率)的时间序列数据;
带行列标签的矩阵数据,包括同构或异构型数据;
任意其它形式的观测、统计数据集, 数据转入 Pandas 数据结构时不必事先标记。
数据结构:
Pandas 的主要数据结构是 Series(带标签的一维同构数组)与 DataFrame(带标签的,大小可变的,二维异构表格),
这两种数据结构足以处理金融、统计、社会科学、工程等领域里的大多数典型用例。
import numpy as np
#导入pandas库
import pandas as pd
1、创建Series,其中index 是轴标签列表。
Series中支持:
Python字典
多维数组
标量值(如,5)
列表创建
#列表创建
x=pd.Series([1,3,4,5,np.nan])#Pandas用NaN(Not a Number)表示缺失数据。
print(x)
y=pd.Series([1,3,4,5,np.nan],index=['A','B','C','D','E'])#序列值默认从0开始,可通过index改变序列值
print(y)
0 1.0
1 3.0
2 4.0
3 5.0
4 NaN
dtype: float64
A 1.0
B 3.0
C 4.0
D 5.0
E NaN
dtype: float64
数组创建pd.Series()
括号内填range、arange,random等numpy数组创建方法
#数组创建pd.Series(),括号内填range、arange,random等numpy数组创建方法
x1=pd.Series(np.arange(1,5),index=['a','b','c','d'])
x1
a 0.0
b 0.0
c 0.0
d 0.0
dtype: float64
python字典创建
Series与字典联系紧密,可以说是字典的列表
#python字典创建,Series与字典联系紧密,可以说是字典的列表
y1=pd.Series({'hello':" hello", 'world!':"world!"})
print(y1)
#Series和字典可以用to_dict方法互相转换
y11=y1.to_dict()
print(y11)
y12=pd.Series(y1.to_dict())
print(y12)
hello hello
world! world!
dtype: object
{'hello': ' hello', 'world!': 'world!'}
hello hello
world! world!
dtype: object
字典创建时Series,同样可通过index改变序列值
#字典创建时Series,同样可通过index改变序列值
a=pd.Series({'a':2,'b':0,'c':3,'d':1})
print(a)
a1=pd.Series({'a':2,'b':0,'c':3,'d':1},index=['b','a','c','d'])
print(a1)
a 2
b 0
c 3
d 1
dtype: int64
b 0.0
a 2.0
c 3.0
d 1.0
e NaN
dtype: float64
2、Series一些方法
#数据类型Series.dtype
print(y1.dtype)
print(a.dtype)
object
int64
#name 属性
y2=pd.Series(np.arange(4),name='number')
print(y2)
print(y2.name)
0 0
1 1
2 2
3 3
Name: number, dtype: int32
number
#切片和索引与多维数组类似
a2=pd.Series(np.random.random(5),index=['a','b','c','d','e'])
print(a2)
#索引输出第二个值
print(a2[1])
#切片,从第二个值开始到第三个值
print(a2[1:3])
#按指定序列输出值
print(a2[[1,0,3,2]])#[1,0,3,2]默认为index参数
a 0.775926
b 0.016618
c 0.366515
d 0.620292
e 0.672258
dtype: float64
0.01661766936240472
b 0.016618
c 0.366515
dtype: float64
b 0.016618
a 0.775926
d 0.620292
c 0.366515
dtype: float64
#numpy.exp():返回e的幂次方,e^x
print(np.exp(a2))
a 2.172603
b 1.016757
c 1.442698
d 1.859470
e 1.958655
dtype: float64
Series.array,Series.to_numpy()提取 Series 数组。
b=pd.Series(np.linspace(1,9,5),index=['A','B','C','D','E'])
print(b)
print(b.array)#所提取的为pandas的扩展数组
print(b.to_numpy())#返回Numpy的多维数组
A 1.0
B 3.0
C 5.0
D 7.0
E 9.0
dtype: float64
<PandasArray>
[1.0, 3.0, 5.0, 7.0, 9.0]
Length: 5, dtype: float64
[1. 3. 5. 7. 9.]
矢量操作,Series的运算
print(b)
#加法
print(b+b)
#切片加法会自动对齐标签
print(b[:5]+b[2:])
A 1.0
B 3.0
C 5.0
D 7.0
E 9.0
dtype: float64
A 2.0
B 6.0
C 10.0
D 14.0
E 18.0
dtype: float64
A NaN
B NaN
C 10.0
D 14.0
E 18.0
dtype: float64