Pandas——loc、iloc、ix 函数区别

1、loc函数

通过行标签索引行数据。
可以多行,可以[行标签, 列标签]

import pandas as pd
import numpy as np

data = [[1, 2, 3],[4, 5, 6]]
index1 = [10, 11]
index2 = ['d', 'e']
colums = ['a', 'b', 'c']
df1 = pd.DataFrame(data=data, index=index1, columns=colums)
df2 = pd.DataFrame(data=data, index=index2, columns=colums)

# print(df)
# loc——通过行标签索引行数据
print(df1.loc[11])
print(df2.loc['d'])
# print(df1.loc['a'])  ## 只能时行索引
print(df2.loc['d':])   ## 多行索引
print(df2.loc['d',['b','c']])  ## 扩展:索引某行某列
print(df2.loc[:,['c']])
## 获取某列 df.[列标签]
## 注意:df[1:3]包含1,2,3

输出结果

a    4
b    5
c    6
Name: 11, dtype: int64
a    1
b    2
c    3
Name: d, dtype: int64
   a  b  c
d  1  2  3
e  4  5  6
b    2
c    3
Name: d, dtype: int64
   c
d  3
e  6

2、iloc函数

通过行号索引行数据。

# iloc——通过行号获取行数据
print(df2.iloc[1])
# print(df2.iloc['a'])  # 通过行标签索引会报错
print(df2.iloc[0:])     ## 多行
print(df2.iloc[:,[1]])  ## 列数据

输出结果

a    4
b    5
c    6
Name: e, dtype: int64
   a  b  c
d  1  2  3
e  4  5  6
   b
d  2
e  5

3、ix函数

结合前两种的混合索引

# ix——结合前两种的混合索引
print(df2.ix[1])
print(df2.ix['e'])

输出结果

a    4
b    5
c    6
Name: e, dtype: int64
a    4
b    5
c    6
Name: e, dtype: int64
  • 6
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值