pandas索引操作(含 loc和iloc)


前言

pandas索引操作与数组切片很相似,但也有不同,那不同呢?快来找找吧!

Series 与 DataFrame 索引

可以用位置切片(不包含末端索引) 也可以用标签切片(包含末端索引)

1.不借助任何东西

1.series:

import pandas as pd

ds = pd.Series([1,2,3,4,5],index=["A","B","C","D","E"])
# 连续
print(ds[1:])
# 1    2
# 2    3
# 3    4
# 4    5
# dtype: int64

# 不连续
print(ds[[1,3]])
print(ds[["B","D"]])
# 1    2
# 4    5
# dtype: int64
  1. DataFrame:

代码如下(示例):

pf1 = pd.DataFrame(np.arange(16).reshape(4,4),index=["a","b","c","d"],columns=["A","B","C","D"])
#     A   B   C   D
# a   1   2   3   4
# b   5   6   7   8
# c   9  10  11  12
# d  13  14  15  16
print(pf1[:1])  # 取行
print(pf1["A"])  # 取列 只能用标签
print(pf1[["A","C","D"]])  # 取多列
print(pf1["A"][1])  # 取单个数

2.高级索引 借助 (iloc 与 loc)

  1. iloc 位置索引

代码如下(示例):

print(pf1.iloc[:3,:3])  # 连续
print(pf1.iloc[:3,[1,3]])  # 列不连续
  1. loc 标签索引

代码如下(示例):

print(pf1.loc["a":"c","A":"C"])  # 连续
print(pf1.loc[["a","d"],["A"]])  # 不连续

总结

pandas索引操作就是基本操作中的"查"

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值