对于机器学习的研究者,无论是数据分析还是数据挖掘,Pandas是一个非常重要的Python包,它不仅提供了很多方法,使得数据处理非常简单,同时在数据处理速度上也做了很多优化,在一定程度上优于Python的内置方法。
如果你想学习Pandas,建议看一下pandas的官网:Python Data Analysis Library
我们从基础开始一步步说起:
创建序列方法一:
'''
pandas
1、结构化数据分析
2、DataFrame、series等
3、强大的索引和数据处理能力
'''
import pandas as pd
from pandas import Series,DataFrame
#pandas series
#创建序列
s1=pd.Series([21,22,3,4])
s1
>>>0 21
1 22
2 3
3 4
dtype: int64
求序列的值
s1.values
>>>array([21, 22, 3, 4], dtype=int64)
求序列的索引
s1.index
>>>RangeIndex(start=0, stop=4, step=1)
默认索引是从0开始,如果想自定义索引
s2=Series([23,24,56,12],index=['A','B','C','D'])
s2
>>>A 23
B 24
C 56
D 12
dtype: int64
生成的序列同样可以使用切片
s2[2:]
>>C 56
D 12
dtype: int64
如果想要从序列中查找某些指定的内容
s2[s2>20]
>>>A 23
B 24
C 56
dtype: int64
将序列转换为字典
s2.to_dict()
>>>{'A': 23, 'B': 24, 'C': 56, 'D': 12}
当索引和内容不匹配时,若内容多出来,会报错;如果是索引多,则会默认给多出的索引一个空值
s2=Series([23,24,56,12],index=['A','B','C','D'])
index01=['A','B','C','D','e1']
s4=Series(s2,index01)
s4
>>>A 23.0
B 24.0
C 56.0
D 12.0
e1 NaN
dtype: float64
判断序列是否为空
pd.isnull(s4)
pd.notnull(s4)
>>>A True
B True
C True
D True
e1 False
dtype: bool
创建序列方法二
import numpy as np
s11=Series(np.arange(5))
s11
>>>0 0
1 1
2 2
3 3
4 4
dtype: int32
创建序列方法三
s12=Series({'A':1,'B':2,'C':3})
s12
>>>A 1
B 2
C 3
dtype: int64
reindex,这里说明一下,reindex更多的不是修改pandas对象的索引,而只是修改索引的顺序,如果修改的索引不存在就会使用默认的NaN代替此行。且不会修改原数组,要修改需要使用赋值语句。
s12.reindex(index=['a','b','c'])