本文共 3472 字,大约阅读时间需要 11 分钟。
数据类型的操作
改变Series和DataFrame对象
重新索引: 使用reindex()改变和重排Series和DataFrame索引 方法:index指索引,cloumns表示第一行索引,后面还可以接上更多参数.reindex(index=None,cloumns=None,.....)
使用以下代码,会发现重新索引后出现的都是NaN,新加的索引并不会存在旧值,这个时候会产生缺省,缺省使用NaN补齐
>>> a={ 'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([4,5,6,7],index=['a','b','c','d'])}>>> b=pd.DataFrame(a)>>> b one twoa 1.0 4b 2.0 5c 3.0 6d NaN 7>>> b=b.reindex(index=['q','w','e','r'])>>> b one twoq NaN NaNw NaN NaNe NaN NaNr NaN NaN#使用上述定义好的b,注意,b的值已经被改变了,再一次运行生成b的代码>>> b=b.reindex(columns=['three','four'])>>> b three foura NaN NaNb NaN NaNc NaN NaNd NaN NaN
参数表
参数名 | 描述 |
---|---|
index 、clumns | 新的行列自定义索引 |
fill_value | 重新索引中,用于填充缺失位置的值 |
method | 填充方法,ffill当前值向前填充,bfill向后填充 |
limit | 最大填充量 |
copy | 默认为True,生成新对象。为False时,新旧相等不复制 |
代码案例:以上述代码b原本为例
>>> b.indexIndex(['a', 'b', 'c', 'd'], dtype='object')>>> b.indexIndex(['one', 'two'], dtype='object')
通过上述代码我们发现,b.index b.index的数据类型都是Index(索引类型)
索引类型的常用的方法
方法名 | 描述 |
---|---|
.append(idx) | 连接另一个index对象,产生一个新的Index对象 |
.diff(idx) | 计算差集,产生一个新的Index对象 |
.intersection(idx) | 计算交集,产生一个新的Index对象 |
.union(idx) | 计算并集,产生一个新的Index对象 |
.delete() | 删除loc位置的元素 |
/insert(loc,e) | 在loc位置新增一个元素e |
案例代码如下
>>> b one twoa 1.0 4b 2.0 5c 3.0 6d NaN 7>>> nc=b.columns.delete(1)>>> ncIndex(['one'], dtype='object')>>> ni=b.index.insert(5,'100')>>> nd=b.reindex(index=ni,columns=nc,method='ffill')>>> nd onea 1.0b 2.0c 3.0d NaN100 NaN
删除Series和DataFrame指定行和索引列
使用.drop()
案例代码如下:在操作DataFrame对象时,需要制定axis,而操作Series对象则不需要指定,因为axis,默认为0值 >>> b one twoa 1.0 4b 2.0 5c 3.0 6d NaN 7>>> b.drop(['a']) one twob 2.0 5c 3.0 6d NaN 7>>> b.drop('one',axis=1) twoa 4b 5c 6d 7
数据类型的运算
1.0 算术运算:
案例代码如下:- 、 * 、 / 、
同理
>>> import numpy as np>>> import pandas as pd>>> a=pd.DataFrame(np.arange(12).reshape(3,4))>>> a 0 1 2 30 0 1 2 31 4 5 6 72 8 9 10 11>>> b=pd.DataFrame(np.arange(20).reshape(4,5))>>> b 0 1 2 3 40 0 1 2 3 41 5 6 7 8 92 10 11 12 13 143 15 16 17 18 19>>> a+b 0 1 2 3 40 0.0 2.0 4.0 6.0 NaN1 9.0 11.0 13.0 15.0 NaN2 18.0 20.0 22.0 24.0 NaN3 NaN NaN NaN NaN NaN
方法形式运算,优势在于可以添加参数
方法名 | 描述 |
---|---|
.add(a,**argws) | 加 |
.sub(a,**argws) | 减 |
.mul(a,**argws) | 乘 |
.div(a,**argws) | 除 |
案例代码
表示将NaN的值补齐为100,再参与运算 # a和 b的值沿用上述代码>>> b.add(a,fill_value=100) 0 1 2 3 40 0.0 2.0 4.0 6.0 104.01 9.0 11.0 13.0 15.0 109.02 18.0 20.0 22.0 24.0 114.03 115.0 116.0 117.0 118.0 119.0
不同维度的运算
将进行广播运算:案例代码:>>> c=pd.Series(np.arange(5))>>> c-10 #一维与0维之间0 -101 -92 -83 -74 -6dtype: int32>>> b-c #二维与一维之间的运算 0 1 2 3 40 0 0 0 0 01 5 5 5 5 52 10 10 10 10 103 15 15 15 15 15
2.0 比较运算:
案例代码:其他比较同理。
>>> a=pd.DataFrame(np.arange(12).reshape(3,4))>>> d = pd.DataFrame(np.arange(12, 0, -1).reshape(3, 4))>>> a>d 0 1 2 30 False False False False1 False False False True2 True True True True#不同维度之间进行比较>>> a>c #二维对一维进行比较 0 1 2 3 40 False False False False False1 True True True True False2 True True True True False>>> c>0 #一维对0维进行比较0 False1 True2 True3 True4 Truedtype: bool
转载地址:http://tamzi.baihongyu.com/