Series
Series是一种类似于数组的对象,它由一种数据以及一组与之相关的数据索引组成。
from pandas import Series,DataFrame
import pandas as pd
import numpy as np
obj = Series([4,7,-5,3])
obj
Out[3]:
0 4
1 7
2 -5
3 3
dtype: int64
obj.values
Out[4]: array([ 4, 7, -5, 3], dtype=int64)
obj.index
Out[5]: RangeIndex(start=0, stop=4, step=1)
obj2 = Series([4,7,-5,3], index=['d','b','a','c'])
obj2
Out[7]:
d 4
b 7
a -5
c 3
dtype: int64
obj2.index
Out[8]: Index(['d', 'b', 'a', 'c'], dtype='object')
obj2['a']
Out[9]: -5
obj['d']=-6
obj2
Out[11]:
d 4
b 7
a -5
c 3
dtype: int64
obj2[['c','a','d']]
Out[12]:
c 3
a -5
d 4
dtype: int64
obj2['d']=-6
obj2
Out[14]:
d -6
b 7
a -5
c 3
dtype: int64
obj2[obj2>0]
Out[15]:
b 7
c 3
dtype: int64
obj2*2
Out[16]:
d -12
b 14
a -10
c 6
dtype: int64
np.exp(obj2)
Out[19]:
d 0.002479
b 1096.633158
a 0.006738
c 20.085537
dtype: float64
'b'in obj2
Out[20]: True
'e' in obj2
Out[21]: False
也可以直接通过字典来创建Series
sdata = {'李白':850,'元歌':980,'程咬金':420,'蔡文姬':120}
obj3 = Series(sdata)
obj3
Out[24]:
李白 850
元歌 980
程咬金 420
蔡文姬 120
dtype: int64
states = ['蔡文姬','程咬金','孙尚香','元歌']
obj4 = Series(sdata,index = states)
obj4
Out[27]:
蔡文姬 120.0
程咬金 420.0
孙尚香 NaN
元歌 980.0
dtype: float64
pd.isnull(obj4)
Out[28]:
蔡文姬 False
程咬金 False
孙尚香 True
元歌 False
dtype: bool
obj4.isnull()
Out[30]:
蔡文姬 False
程咬金 False
孙尚香 True
元歌 False
dtype: bool
obj3 + obj4
Out[31]:
元歌 1960.0
孙尚香 NaN
李白 NaN
程咬金 840.0
蔡文姬 240.0
dtype: float64
obj4.name = '物理攻击'
obj4.index.name = '英雄'
obj4
Out[34]:
英雄
蔡文姬 120.0
程咬金 420.0
孙尚香 NaN
元歌 980.0
Name: 物理攻击, dtype: float64
也可以改变索引值
obj.index = ['红','黄','蓝','绿','紫']
obj
Out[38]:
红 4
黄 7
蓝 -5
绿 3
紫 -6
dtype: int64