Python -- pandas

标签(空格分隔): Python


数据结构

#首先引入需要使用的模块
from pandas import Series, DataFrame
import pandas as pd

Series

Series类似于一维数组的对象,由一组数据以及一组与之相关的数据标签组成。传入一个数组,将会创建一个0-N-1的整数型索引。

In[]: obj = Series([2,3,4,-3])
In[]: obj.values
In[]: obj.index
In[]: obj = Series([2,3,4,-3], index=['d', 'b', 'a', 'c']) # 为键值指定索引
In[]: obj['a'] #取出相应索引位置的值
In[]: obj[obj > 0]
In[]: obj * 2
In[]: np.exp(obj)
In[]: 'b' in obj
In[]: sdata = {'Ohio' : 35000, 'Texas' : 71000, 'Oregen' : 16000, 'Utath' : 5000} # 创建一个词典
In[]: obj2 = Series(sdata) # 用字典创建Series
In[]: states = ['California', 'Oregen', 'Utath', 'Ohio', 'Texas']
In[]: obj3 = Series(sdata, index = states) # 缺失值用NA表示
In[]: pd.isnull(obj3) # 检测缺失值
In[]: obj.isnull()
In[]: obj3.name = 'population' # 指定表的名字
In[]: obj3.index.name = 'state' # 指定列的名字

DataFrame

DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型。既有行索引,又有列索引。DataFrame中面向行的和面向列的操作基本是平衡的,它的数据是由一个或多个二维块存放的。

In[]: data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year' : [2000, 2001, 2002, 2001, 2002], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
In[]: frame = DataFrame(data)
In[]: DataFrame(data, clolumns = ['state', 'pop', 'year']) # DataFrame的列按照指定的顺序排序
In[]: frame2 = DataFrame(data, columns = ['year', 'state', 'pop', 'debt'], index=['one', 'two', 'three', 'four', 'five']) # 如果指定的列在原数据中找不到,则用NA填充
In[]: frame2['eastern'] = frame2.state == 'Ohio'
In[]: del frame2['earstern']

In[]: pop = {'Nevada' : {2001:2.4, 2002:2.9}, 'Ohio' : {2000:1.5, 2002:3.6}} # 用嵌套字典创建DataFrame,外层字典的键作为列,内层键作为行索引
In[]: frame3 = DataFrame(pop)

索引对象

pandas的索引对象负责管理轴标签和其他元数据。index对象是不可以修改(immutable)的。

In[]: obj = Series(range(3), index = ['a', 'b', 'c'])
In[]: index = obj.index
In[]: index[1:]
In[]: index[1] = 'f' # 测试一下能不能修改

In[]: index = pd.Index(np.arange(3))
In[]: obj = Series([1.5, -2.5, 0], index = index)
In[]: obj.index = index
In[]: index is obj.index # True

pandas中主要的index对象:

说明
Index最泛化的Index对象,将轴标签表示为一个有Python对象组成的Numpy数组
Int64Index针对整数的特殊Index
MultiIndex“层次化”索引对象,表示单个轴上的多层索引。可以看做由元组组成的数组
DatetimeIndex存储纳秒级的时间戳
PeriodIndex针对Period数据的特殊Index

index的方法和属性:

方法说明
append连接另一个Index对象,产生一个新的Index
diff计算差集,并得到一个Index
intersection计算交集
union计算并集
isin计算一个指示各值是否都包含在参数集合中的布尔型数值
delete删除索引i处的元素,并得到新的Index
drop删除传入的值,并得到新的Index
insert将元素插入到索引i处,并得到新的Index
is_monottonic当各元素均大于等于前一个元素时,返回True
is_unique当Index没有重复值时,返回True
unique计算Index中唯一值的数组

重新检索:

In[]: obj = Series([4.5, 7.2, -5.3, 3.6], index = ['d', 'b', 'a', 'c'])
In[]: obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value = 0) # 不存在的index用o填充
In[]: obj3 = Series(['blue', 'purple', 'yellow'], index = [0,2,4])
In[]: obj3.reindex(range(6), method = 'ffill')

reindex的插值的method选项:

参数说明
ffill 或 pad前向填充
bfill 或 backfill后向填充

reindex函数的参数:

参数说明
index用作索引的新索引。
method插值(填充方式)
fill_value在重新检索的过程中,需要引入缺失值时使用的替代值
limit前向或后向填充时的最大填充量
level在MultiIndex的指定级别上匹配简单索引,否则选取其子集
copy默认为True

* 丢弃指定轴上的数据:

# Sereis中的drop()操作
In[]: obj = Series(np.arange(5), index=['a', 'b', 'c', 'd', 'e'])
In[]: new_obj = obj.drop('a')
In[]: obj.drop(['a', 'b'])

# DataFrame中的drop()操作
In[]: data = DataFrame(np.arange(16).reshape((4, 4)), index = ['a', 'b', 'c', 'd'], columns = ['one', 'two', 'three', 'four'])
In[]: data.drop(['a', 'b'])
In[]: data.drop(['one', 'four'], axis = 1)

索引、选取和过滤

Series索引(obj[…])的工作方式与Numpy中的数组索引类似,只不过Series的索引值不只是整数。

# Sereis中的索引和切片操作
In[]: obj = Series(np.arange(4), index=['a','b','c','d'])
In[]: obj['b'] # 1
In[]: obj[1] # 1
In[]: obj[2:4] # c 2 d 3
In[]: obj[['a', 'c']] # 0 2
In[]: obj[obj < 2] # a 0 b 1
In[]: obj['b':'c'] # b 1 c 2(该切片是包含末端的!!)
In[]: obj['b':'c'] = 5 # 将索引为b->c的设置为5

# DataFrame中的索引和切片操作
In[]: data = DataFrame(np.arange(16).reshape(4, 4), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['1', '2', '3', '4'])
In[]: data.ix['Colorado', ['2', '3']] # **使用ix进行行索引**
In[]: data.ix[data.3 > 5, :3]

DataFrame的索引选项:

类型说明
obj[val]选取DataFrame的单个列或一组列。
obj.ix[val]选取DataFrame的单个行或一组行。
obj.ix[:, val]选取单个列或列子集
obj.ix[val1, val2]同时选取行和列
reindex方法将一个或多个轴匹配到新索引
xs方法根据标签选取单行或单列,并返回一个Series
icol, irow方法根据整数位置选取单列或单行,并返回一个Series
get_value, set_value方法根据行标签和列标签选取单个值

算术运算和数据对齐

In [62]: s1 = Series([7.3,-2.5,3.4,1.5], index=['a', 'c', 'd', 'e'])
In [63]: s2 = Series([-2.1, 3.6,-1.5,4,3.1], index=['a', 'c', 'e', 'f', 'g'])
In [64]: s1
Out[64]: 
a    7.3
c   -2.5
d    3.4
e    1.5
dtype: float64

In [65]: s2
Out[65]: 
a   -2.1
c    3.6
e   -1.5
f    4.0
g    3.1
dtype: float64

In [66]: s1 + s2
Out[66]: 
a    5.2
c    1.1
d    NaN
e    0.0
f    NaN
g    NaN
dtype: float64


In [67]: df1 = DataFrame(np.arange(9.).reshape((3,3)), columns=list('bcd'), index=['Ohio', 'Texas', 'Colorado'])

In [68]: df2 = DataFrame(np.arange(12.).reshape((4,3)), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon'])

In [69]: df1
Out[69]: 
            b    c    d
Ohio      0.0  1.0  2.0
Texas     3.0  4.0  5.0
Colorado  6.0  7.0  8.0

In [70]: df2
Out[70]: 
          b     d     e
Utah    0.0   1.0   2.0
Ohio    3.0   4.0   5.0
Texas   6.0   7.0   8.0
Oregon  9.0  10.0  11.0

In [71]: df1 + df2
Out[71]: 
            b   c     d   e
Colorado  NaN NaN   NaN NaN
Ohio      3.0 NaN   6.0 NaN
Oregon    NaN NaN   NaN NaN
Texas     9.0 NaN  12.0 NaN
Utah      NaN NaN   NaN NaN

In[]: df1.add(df2, fill_value=0) # 两个矩阵相加,没有值的位置填入0补充
In[]: df1.reindex(columns = df2.columns, fill_value=0)

In[]: f = lambda x: x.max() - x.min()
In[]: frame.apply(f)
In [98]: def f(x):
...:     return Series([x.min(), x.max()], index=['min', 'max'])
...: 

In [99]: frame.apply(f)
Out[99]: 
            b         d         e
min -2.789435 -0.110705 -1.101437
max  0.653851  1.258250  1.592027

In[]: format = lambda x: '%2.f' % x
In[]: frame.applymap(format) # for DataFrame

In[]: frame['b'].map(format) # for Series

排序和排名

根据条件对数据集排序,要对行或列索引进行排序,使用index_sort方法进行排序。

In[]: obj = Series(range(4), index=['b', 'a', 'c', 'd'])
In[]: obj.sort_index()
In [109]: frame = DataFrame(np.arange(8).reshape((2, 4)), index=['three','one'], columns=list('
 ...: dabc'))

In [110]: frame
Out[110]: 
       d  a  b  c
three  0  1  2  3
one    4  5  6  7

In [111]: frame.sort_index()
Out[111]: 
       d  a  b  c
one    4  5  6  7
three  0  1  2  3

In[]: frame.sort_index(axis=1, ascending=False)
In[]: obj = Series([4,7,-3,2])
In[]: obj.order() # 任何缺失值会被方法哦Series末尾

In [119]: frame = DataFrame({'b':[4,7,-3,2], 'a':[0,1,0,1]})

In [120]: frame
Out[120]: 
   a  b
0  0  4
1  1  7
2  0 -3
3  1  2

In [121]: frame.sort_index(by='b')
Out[121]: 
   a  b
2  0 -3
3  1  2
0  0  4
1  1  7

汇总和计算描述统计

约简方法的选项:

选项说明
axis约简的轴。DataFrame的行用0,列用1
skipna排除缺失值,默认为True
level如果轴是层次化索引的,则根据level分组约简

相关系数与协方差

import pandas.io.data as web
all_data = {}
for ticker in ['AAPL', 'IBM', 'MSFT', 'GOOG']: all_data[ticker] = web.getd_data_yahoo(ticker, '1/1/2000', '1/1/2010')
price = DataFrame({tic:data['Adj Close'] for tic, data in all_data.iteritems()})
volume = DataFrame({tic:data['Volume'] for tic, data in all_data.iteritems()})

In[]: returns = price.pct_change()
In[]: returns.tail()
In[]: returns.MSFT.corr(returns.IBM) # 计算Series的相关系数
In[]: returns.MSFT.cov(returns.IBM) # 计算Series的协方差

In[]: returns.corr() # 计算DataFrame的相关系数
In[]: returns.cov() # 计算DataFrame的协方差

唯一值、值计数及成员资格

In[]: obj = Series(['c', 'a', 'd', 'a', 'a', 'b', 'b', 'c', 'c'])
In[]: unique = obj.unique()
In[]: obj.value_counts()

处理缺失数据

方法说明
dropna根据标签中的值中是否存在缺失数据对轴标签进行过滤,可通过阈值调节对缺失值的容忍度
fillna用指定值或插值方法ffill或bfill填充缺失数据
isnull返回一个含有布尔值的对象,这些布尔值表示哪些值是缺失值
notnullisnull的否定式
In[]: df = DataFrame(np.random.randn(3, 7))
In[]: from numpy import nan as NA
In[]: df.ix[:4, 4] = NA; df.ix[:2, 2] = NA
In[]: df.fillna(0) # 将所有的nan值替换为0
In[]: df.fillna({1:0.5, 3:-1})
In[]: df.fillna(method = 'ffill', limit=2)
In[]: data = Series([1., NA, 7., NA, 3.5])
In[]: data.ffill(data.mean()) # 用数组的均值填充(很有用哦)
  • fillna函数的参数
参数说明
value用于填充缺失值的标量值或字典对象
method表明插值方式。默认为“ffill – 前向填充”
axis待填充的轴,默认为axis = 0
inplace修改调用者对象而不产生副本
limit(对于前向和后向填充)可以连续填充的最大数量

层次化索引(hierarchical indexing)

它使我们能够在一个轴上拥有多个索引级别。

In [35]: data = Series(np.random.randn(10), index=[['a','a','a','b','b','b','c','c','d','d'],[1
...: ,2,3,1,2,3,1,2,2,3]])

In [36]: data
Out[36]: 
a  1   -0.335981
   2   -1.771950
   3    0.847548
b  1    1.806644
   2   -0.550041
   3    0.409235
c  1    1.429005
   2    1.111154
d  2   -0.769956
   3    1.675767
dtype: float64
In [37]: data.index
Out[37]: 
MultiIndex(levels=[[u'a', u'b', u'c', u'd'], [1, 2, 3]],
           labels=[[0, 0, 0, 1, 1, 1, 2, 2, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 1, 2]])
In[]: data['a']
In[]: data.ix[['a', 'c']]
In[]: data['b': 'd']

In [50]: data[:, 1] # 对内层进行索引,显示
Out[50]: 
a   -0.335981
b    1.806644
c    1.429005

# 用unstack将多层索引Series映射到一个DataFrame中
In [51]: data.unstack()
Out[51]: 
          1         2         3
a -0.335981 -1.771950  0.847548
b  1.806644 -0.550041  0.409235
c  1.429005  1.111154       NaN
d       NaN -0.769956  1.675767

#用stack()将DataFrame重新索引到一个Series中
In [52]: data.unstack().stack()
Out[52]: 
a  1   -0.335981
   2   -1.771950
   3    0.847548
b  1    1.806644
   2   -0.550041
   3    0.409235
c  1    1.429005
   2    1.111154
d  2   -0.769956
   3    1.675767

In [53]: df = DataFrame(np.arange(12).reshape(4,3), index = [['a','a','b','b'],[1,2,1,2]], colu
    ...: mns = [['Ohio','Ohio', 'Colorado'], ['Green', 'Red', 'Green']])

In [54]: df
Out[54]: 
     Ohio     Colorado
    Green Red    Green
a 1     0   1        2
  2     3   4        5
b 1     6   7        8
  2     9  10       11

In [55]: df.index.names = ['key1', 'key2']

In [56]: df
Out[56]: 
           Ohio     Colorado
          Green Red    Green
key1 key2                   
a    1        0   1        2
     2        3   4        5
b    1        6   7        8
     2        9  10       11

# 重新分级排序
In [63]: df.swaplevel('key1', 'key2')
Out[63]: 
state      Ohio     Colorado
color     Green Red    Green
key2 key1                   
1    a        0   1        2
2    a        3   4        5
1    b        6   7        8
2    b        9  10       11
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值