鉴于ix已弃用,为pandas 0.20更新。这不仅演示了如何使用loc, iloc, at, iat, set_value,还演示了如何完成基于位置/标签的混合索引。
基于Loc标签
允许您传递1-D数组作为索引器。数组可以是索引或列的切片(子集),也可以是长度与索引或列相等的布尔数组。
特别注意:当传递标量索引器时,loc可以分配一个以前不存在的新索引或列值。
# label based, but we can use position values
# to get the labels from the index object
df.loc[df.index[2], 'ColName'] = 3
df.loc[df.index[1:3], 'ColName'] = 3
Iloc -基于职位
类似于loc,除了位置而不是索引值。但是,不能分配新的列或索引。
# position based, but we can get the position
# from the columns object via the `get_loc` method
df.iloc[2, df.columns.get_loc('ColName')] = 3
df.iloc[2, 4] = 3
df.iloc[:3, 2:4] = 3
基于标签的
工作原理与用于标量索引器的loc非常相似。不能操作数组索引器。可以!分配新的索引和列。
与loc相比,它的优点是更快。
缺点是不能将数组用于索引器。
# label based, but we can use position values
# to get the labels from the index object
df.at[df.index[2], 'ColName'] = 3
df.at['C', 'ColName'] = 3
Iat -基于职位
类似于iloc。不能在数组索引器中工作。不能!分配新的索引和列。
与iloc相比,它的优点是更快。
缺点是不能将数组用于索引器。
# position based, but we can get the position
# from the columns object via the `get_loc` method
IBM.iat[2, IBM.columns.get_loc('PNL')] = 3
Set_value -基于标签
工作原理与用于标量索引器的loc非常相似。不能操作数组索引器。可以!分配新的索引和列
优势超快,因为开销很小!
缺点:由于熊猫没有做一堆安全检查,所以开销很小。使用风险自负。此外,这不是为公共用途。
# label based, but we can use position values
# to get the labels from the index object
df.set_value(df.index[2], 'ColName', 3)
set_value with takable=True -基于位置
类似于iloc。不能在数组索引器中工作。不能!分配新的索引和列。
优势超快,因为开销很小!
缺点:由于熊猫没有做一堆安全检查,所以开销很小。使用风险自负。此外,这不是为公共用途。
# position based, but we can get the position
# from the columns object via the `get_loc` method
df.set_value(2, df.columns.get_loc('ColName'), 3, takable=True)