博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Pandas数据类型的操作
阅读量:3958 次
发布时间:2019-05-24

本文共 1694 字,大约阅读时间需要 5 分钟。

改变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

转载地址:http://vamzi.baihongyu.com/

你可能感兴趣的文章