python pandas中的ix,loc和iloc

本文介绍了Python pandas库中DataFrame的ix, loc和iloc三种数据选择方法。ix是混合索引和位置定位,loc是纯标签定位,而iloc是纯位置定位。在使用时,推荐使用df.loc[:,'one']来修改行/列,df.loc['a','one']来修改特定元素,避免使用可能返回不确定性的df['one']或df['a']['one']。" 131453289,1467541,从飞机发明看预先要求与必然结果:人工智能的理论根基,"['科学基础', '技术发展', '历史案例', '人工智能理论', '数据模型']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境:python 3.4 + pandas 0.19.1

先看一下官方文档对这3个api的描述:

  • DataFrame.ix
    • A primarily label-location based indexer, with integer position fallback.【支持根据索引值,或者按顺序位置定位】
    • .ix[] supports mixed integer and label based access. It is primarily label based, but will fall back to integer positional access unless the corresponding axis is of integer type.【按顺序位置定位,要求索引不能是数字】
  • DataFrame.loc
    • Purely label-location based indexer for selection by label.【按索引值定位】
    • .loc[] is primarily label based, but may also be used with a boolean array.
  • DataFrame.iloc
    • Purely integer-location based indexing for selection by position.【按顺序位置定位】
    • .iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array.
然后在一个函数中需要对DF进行修改,使用了iloc,但是用的是交叉的方式(df.iloc[1, 'col1'],index使用位置,column使用了索引值),结果发现修改没有生效,报出了警告:
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
里面提到“When setting values in a pandas object, care must be taken to avoid what is called chained indexing. ”,具体详细内容参见链接,不细讲。简单说一下结论:当需要修改pandas的对象时(Series/DataFrame),以如下规则(对ix/loc/iloc一样):
  • 应该使用的方法:df.loc[:,'one'](修改行/列),df.loc['a', 'one'](修改具体某个元素);
  • 不应使用的方法:df['one'](修改行/列),df['a']['one']、df.loc['a']['one'](修改具体某个元素)。(因为这些方法可能返回的是copy,也可能不是,具有不确定性)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值