Index对象

【说明】文章内容来自《机器学习入门——基于sklearn》,用于学习记录。若有争议联系删除。   

1、Index简介        

        创建series或DataFrame等对象时,索引都会被装换为Index对象。Index对象可以通过pandas.Index函数创建,也可以通过创建数据对象series、DataFrame时接收index(或column)参数创建,前者属于显式创建,后者属于隐式创建。

        隐式创建中,通过访问index(或针对DataFrame的column)属性即可得到Index。创建的Index对象不可修改,保证了Index对象在各个数据结构之间的安全共享。

Index对象常用属性如下:

        1.is_monotonic:当各元素均大于前一个元素时返回True。

        【说明】新版本中,用is_monotonic_increasing代替该功能。

        2.is_unique:当Index没有重复值时返回True。

2、创建index对象

import pandas as pd
df = pd.DataFrame({'col1': [1, 2, 3, 4], 'col2': [5, 6, 7, 8]}, index = ['a', 'b', 'c', 'd'])
print('df中的index:\n',df.index)
print('df中index各元素是否均大于前一个元素:\n',df.index.is_monotonic_increasing)
print('df中index各元素是否唯一:\n',df.index.is_unique)

【运行结果】

3、Index对象常用方法:

  1. append:连接另一个Index对象,产生一个新的Index对象。
  2. difference:计算两个Index对象的差集,得到一个新的Index对象。
  3. intersection:计算两个Index对象的交集。
  4. union:计算两个Index对象的并集。
  5. isin:计算一个Index对象是否在另一个Index 对象中,返回bool数组。
  6. delete:删除指定Index 对象的元素,并得到新的Index对象。
  7. drop:删除传人的值,并得到新的Index对象。
  8. insert:将元素插入指定Index对象中,并得到新的Index对象。
  9. unique:计算Index对象中唯一值的数组。

示例

import pandas as pd
df1 = pd.DataFrame({'col1': [0, 1, 2, 3]}, index = ['a', 'b', 'c', 'd'])
df2 = pd.DataFrame({'col2': [5, 6, 7, 8, 9]}, index = ['e', 'f', 'g', 'h', 'i'])
index1 = df1.index
index2 = df2.index
print('index1连接index2后的结果为:\n',index1.append(index2))
print('index1与index2的差集为:\n',index1.difference(index2))
print('index1与index2的交集为:\n',index1.intersection(index2))
print('index1与index2的并集为:\n',index1.union(index2))
print('index1中各元素是否在index2中:\n',index1.isin(index2))
print(index1.delete(2))#删除制定index元素

【运行结果】

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值