数据分析框架Pandas进阶

广播运算

多维数据和一维数据进行运算称为广播,会自动按标签匹配对每个元素执行运算。

In [13]: frm
Out[13]:
   0  1  2
a  0  1  2
b  3  4  5
c  6  7  8
In [16]: sr2 = Series([3,2,4],index = range(3))

In [17]: frm + sr2
Out[17]:
   0  1   2
a  3  3   6
b  6  6   9
c  9  9  12

如果有不能匹配的标签,值均为NaN

In [18]: sr3 = Series([3,2,4],index =[0,2,3])

In [19]: frm + sr3
Out[19]:
     0   1     2   3
a  3.0 NaN   4.0 NaN
b  6.0 NaN   7.0 NaN
c  9.0 NaN  10.0 NaN

如果要在行上做广播,需要调用方法,并指定axis。这些运算都是在副本上进行,不会影响原始数据。

In [20]: sr4 = Series([3,2,4],index = list('abc'))
In [23]: frm.add(sr4,axis = 0)
Out[23]:
    0   1   2
a   3   4   5
b   5   6   7
c  10  11  12

使用函数

apply函数对每一列(或行)执行指定函数
applymap对每各元素执行操作

排序

sort_index可以按索引字典序排序,可以传入参数axis表示维度,ascending表示方向(True,False)
order按值排序,排序时NaN会被放到末尾
按某列值排序,使用sort_index(by = 指定列标签)

rank返回各元素在排好序后的位置,对于相等的元素,默认返回这些元素位置的平均数

In [7]: sr = Series([1,1,2,2,3])

In [8]: sr.rank()
Out[8]:
0    1.5
1    1.5
2    3.5
3    3.5
4    5.0
dtype: float64

可以使用method关键字使相等元素不返回相同rank,如min,max,first等

In [10]: sr.rank(method = 'first')
Out[10]:
0    1.0
1    2.0
2    3.0
3    4.0
4    5.0
dtype: float64

汇总和计算统计

pandas提供sum,mean等多种统计方法。默认作用于每一列上,若要作用于行上需要指定axis。默认NA的值会自动排除,如果要考虑NA的值,可以设skipna = False
参数:axis,skipna

可使用的方法:
count 非NA值数量
describe 全面信息
min,max
argmin,argmax,(索引)
quantile 计算分位数
sum,mean,median
mad 平均绝对离差
var
std
skew 偏度http://baike.baidu.com/view/1216514.htm
kurt 峰度

偏度和峰度的关系:http://blog.sciencenet.cn/blog-1148346-786610.html
cumsum累积和
cummin,cummax
cumprod
diff 一阶差分http://baike.baidu.com/view/3747559.htm
pct_change 百分数变化y(i) = (x(i)-x(i-1))/x(i)

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

unique(): Series调用,返回array

In [2]: a =Series(['a','c','c','a','d'])

In [3]: b = a.unique()

In [4]: b
Out[4]: array(['a', 'c', 'd'], dtype=object)

value_counts(): Series调用,返回Series,各元素出现次数,按频率降序排列

isin(): Series调用,返回bool型Series,表示元素出现与否

In [9]: a
Out[9]:
0    a
1    c
2    c
3    a
4    d
dtype: object
In [11]: b = a.isin(['a','d'])

In [12]: b

Out[12]:
0     True
1    False
2    False
3     True
4     True
dtype: bool

In [13]: a[b]
Out[13]:
0    a
3    a
4    d
dtype: object

对一个DataFrame的每一列分别统计元素出现次数,可以这样:

In [22]: data = DataFrame({'a':[0,2,4,4,3],'b':[3,4,0,1,2],'c':[1,0,3,2,3]})
In [25]: data
Out[25]:
   a  b  c
0  0  3  1
1  2  4  0
2  4  0  3
3  4  1  2
4  3  2  3

In [23]: t = data.apply(value_counts).fillna(0)

In [24]: t
Out[24]:
     a  b    c
0  1.0  1  1.0
1  0.0  1  1.0
2  1.0  1  1.0
3  1.0  1  2.0
4  2.0  1  0.0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值