pandas数据选择(索引)

import pandas as pd
import numpy as np
dates = pd.date_range('20180101',periods=6)
df = pd.DataFrame(np.arange(24).reshape(6,4),index=dates,columns=['A','B','C','D'])
print(df)  #基本数据
             A   B   C   D
2018-01-01   0   1   2   3
2018-01-02   4   5   6   7
2018-01-03   8   9  10  11
2018-01-04  12  13  14  15
2018-01-05  16  17  18  19
2018-01-06  20  21  22  23

一、索引的基本方法

print(df.A, df['A']) #引用A列的两种方式
2018-01-01     0
2018-01-02     4
2018-01-03     8
2018-01-04    12
2018-01-05    16
2018-01-06    20
Freq: D, Name: A, dtype: int32 2018-01-01     0
2018-01-02     4
2018-01-03     8
2018-01-04    12
2018-01-05    16
2018-01-06    20
Freq: D, Name: A, dtype: int32
print(df[0:2])  #引用行的两种方式
            A  B  C  D
2018-01-01  0  1  2  3
2018-01-02  4  5  6  7
print( df['2018-01-02':'2018-01-04'])
             A   B   C   D
2018-01-02   4   5   6   7
2018-01-03   8   9  10  11
2018-01-04  12  13  14  15

二、loc方法(loc——通过行标签索引行数据 )

print(df.loc['2018-01-02'])  #loc——通过行标签索引行数据 
A    4
B    5
C    6
D    7
Name: 2018-01-02 00:00:00, dtype: int32
print(df.loc['2018-01-02',['A','B']]) #应用在index的基础上之后,可以选取所需的列
A    4
B    5
Name: 2018-01-02 00:00:00, dtype: int32

三、iloc方法(iloc——通过行号索引行数据 )

print(df.iloc[3:5,2:4])
             C   D
2018-01-04  14  15
2018-01-05  18  19
print(df.iloc[[1,3,5],2:4]) #跳行取数
             C   D
2018-01-02   6   7
2018-01-04  14  15
2018-01-06  22  23

四、ix方法–通过行标签或者行号索引行数据(基于loc和iloc 的混合)

print(df.ix[0:3,['A','B']])
            A  B
2018-01-01  0  1
2018-01-02  4  5
2018-01-03  8  9


C:\Users\Administrator\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

五、布尔型索引

print(df[df.A>=8])
             A   B   C   D
2018-01-03   8   9  10  11
2018-01-04  12  13  14  15
2018-01-05  16  17  18  19
2018-01-06  20  21  22  23
print(df.A>=8)
2018-01-01    False
2018-01-02    False
2018-01-03     True
2018-01-04     True
2018-01-05     True
2018-01-06     True
Freq: D, Name: A, dtype: bool
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值