pandas的基本用法(二)——选择数据 | | pandas的基本用法(二)——选择数据 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 本文主要是关于pandas的一些基本用法。 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123#!/usr/bin/env python# _*_ coding: utf-8 _*_import pandas as pdimport numpy as np# Test 1# 定义数据dates = pd.date_range('20170101', periods = 6)print datesdf = pd.DataFrame(np.arange(24).reshape((6, 4)), index = dates, columns = ['A', 'B', 'C', 'D'])print df# Test 1 resultDatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04', '2017-01-05', '2017-01-06'], dtype='datetime64[ns]', freq='D') A B C D2017-01-01 0 1 2 32017-01-02 4 5 6 72017-01-03 8 9 10 112017-01-04 12 13 14 152017-01-05 16 17 18 192017-01-06 20 21 22 23# Test 2# 选择第一列数据print df['A']print df.A# 选择前三行数据print df[0:3]print df['20170101':'20170103']# 根据标签选择print df.loc['20170101']# 选择所有行, 特定列print df.loc[:, ['A', 'B']]# 选择特定行, 特定列print df.loc['20170102', ['A', 'B']]# Test 2 result2017-01-01 02017-01-02 42017-01-03 82017-01-04 122017-01-05 162017-01-06 20Freq: D, Name: A, dtype: int642017-01-01 02017-01-02 42017-01-03 82017-01-04 122017-01-05 162017-01-06 20Freq: D, Name: A, dtype: int64 A B C D2017-01-01 0 1 2 32017-01-02 4 5 6 72017-01-03 8 9 10 11 A B C D2017-01-01 0 1 2 32017-01-02 4 5 6 72017-01-03 8 9 10 11A 0B 1C 2D 3Name: 2017-01-01 00:00:00, dtype: int64 A B2017-01-01 0 12017-01-02 4 52017-01-03 8 92017-01-04 12 132017-01-05 16 172017-01-06 20 21A 4B 5Name: 2017-01-02 00:00:00, dtype: int64# Test 3# 根据行列来选择print df.iloc[3:5, 1:3]# 不连续的选择print df.iloc[[1, 3, 5], 2:4]# 混合选择print df.ix[[1, 3, 5], ['A', 'B']]# 对比选择print df[df.A > 4]# Test 3 result B C2017-01-04 13 142017-01-05 17 18 C D2017-01-02 6 72017-01-04 14 152017-01-06 22 23 A B2017-01-02 4 52017-01-04 12 132017-01-06 20 21 A B C D2017-01-03 8 9 10 112017-01-04 12 13 14 152017-01-05 16 17 18 192017-01-06 20 21 22 23 参考资料 https://www.youtube.com/user/MorvanZhou 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏