pandas有三种数据结构形式,分别是Series,DataFrame和索引对象。
1.Series
Series和一维数组很像,只是它的每一个值都有一个索引,输出显示时索引在左,值在右。
如果语言无法清晰表达,不妨看段代码,毕竟talk is cheap,show me your code!!!
首先导入pandas库:
>>from pandas import Series
用数组生成一个Series:
>>test1=Series([1,2,3,4,5])
>>print test1
输出:
0 1
1 2
2 3
3 4
4 5
dtype: int64
上面的例子我们没有指定索引。没有索引的情况下索引值默认从1开始往后排。
接下来我们尝试用index参数指定索引:
>>test2=Series([2,3,3,3],index=['c','o','d','e'])
c 2
o 3
d 3
e 3
dtype: int64
也可以用字典生成Series:
>>> dic={'h':1,'e':2,'l':3}
>>> test3=Series(dic)
>>> print test3
e 2
h 1
l 3
dtype: int64
OK!以上是Series的生成方法,下面讲Series的使用技巧。
获取Series的索引和值:
>>> print test1.index
RangeIndex(start=0, stop=5, step=1)
>>> print test2.values
[2 3 3 3]
获取特定索引的值:
>>> test1[1]
2
>>> test2['c']
2
>>> test2[['c','o']]
c 2
o 3
dtype: int64
指定Series及其索引的名字:
>>> test3.name='test'
>>> test3.index.name='hello'
>>> print test3
hello
e 2
h 1
l 3
Name: test, dtype: int64
用新的index替换掉旧的index:
>>> test3.index=['g','k','b']
>>> print test3
g 2
k 1
b 3
Name: test, dtype: int64
2.DataFrame
DataFrame是一种表格型数据结构,类似于excel,每一个值都有一个行索引和一个列索引,不同列的数据类型可以不一样,当然,解释没用,上代码:
>>import numpy as np
>>from pandas import Series, DataFrame
先用字典生成一波DataFrame
>>dic={'name':['Bill','Alice','John'],'age':[23,22,18],'sex':[1,0,1]}
>>test1=DataFrame(dic)
age name sex
0 23 Bill 1
1 22 Alice 0
2 18 John 1
可以看到用字典生成的DataFrame只指定了列索引,没指定行索引,那么行索引就默认从0开始往后排。
下面指定索引:
>>test2=DataFrame(dic,columns=['age','name','sex','class'],index=[1,2,3])
>>test2=DataFrame(dic,columns=['age','name','sex','class'],index=[1,2,3])
>>print test2
age name sex class
1 23 Bill 1 NaN
2 22 Alice 0 NaN
3 18 John 1 NaN
可以看到,若指定列不存在,就会用NaN补充。
>>test2['class']=301 #把'class'这列的值都改为301
>>print test2
age name sex class
1 23 Bill 1 301
2 22 Alice 0 301
3 18 John 1 301
还可以转置:
>>test3=test2.T
>>print test3
1 2 3
age 23 22 18
name Bill Alice John
sex 1 0 1
class 301 301 301
3.index
获取索引
test1=Series([1,2,3,4],index=['a','b','c','d'])
index=test1.index #获取index
print index
Index([u'a', u'b', u'c', u'd'], dtype='object')
使用索引对象
index=Index(np.arange(5))
test2=Series([11,22,33,44,55],index=index)
print test2
0 11
1 22
2 33
3 44
4 55
dtype: int64