这一节主要是从DataFrame中进行数据的筛选,对之前两节内容的综合应用。运行环境python2.7
#!usr/bin/python3
# coding:utf-8
import pandas as pd
import numpy as np
dates = pd.date_range("20180110", periods=6)
df = pd.DataFrame(np.arange(24).reshape((6, 4)), index=dates, columns=['A', 'B', 'C', 'D'])
# A B C D
# 2018-01-10 0 1 2 3
# 2018-01-11 4 5 6 7
# 2018-01-12 8 9 10 11
# 2018-01-13 12 13 14 15
# 2018-01-14 16 17 18 19
# 2018-01-15 20 21 22 23
print "df:\n", df
# 效果相同:df['A'], 和, df.A,打印第一列
print "df[['A', 'B']]:\n", df[['A', 'B']]
print "df.A:\n", df.A
# 打印前三行
print "df[0:3]:\n", df[0:3]
# 选择输出2018-01-11到2018-01-13的数据
print "df['20180111':'20180113']:\n", df['20180111':'20180113']
# select by label:loc 通过标签来选择
print "df.loc['20180111']:\n", df.loc['20180111']
# 选择所有的行,列则选择‘A’,‘B’这两列
print "df.loc[:, ['A', 'B']]:\n", df.loc[:, ['A', 'B']]
# 选择2018-01-11到2018-01-13列,列则选择‘A’,‘B’这两列
print "df.loc['20180111':'20180113', ['A', 'B']]:\n", df.loc['20180111':'20180113', ['A', 'B']]
# select by position:iloc
# 打印第三行的数据
print "打印第三行的数据:\n", df.iloc[2]
# 打印第三行中的第一个
print "打印第三行中的第一个:\n", df.iloc[2, 0]
# 以切片的形式展示
# 切片[ )左毕右开
# 筛选地3:5列,1:3行
print "筛选地4和5列,2和3行:\n", df.iloc[3:5, 1:3]
# 筛选2,4,6行,2和3列
print "筛选1,3,5行,1:3列:\n", df.iloc[[1, 3, 5], 1:3]
# 将loc和iloc混合使用
# mix selection:ix
print "筛选2和3行,A和C列:\n", df.ix[1:3, ['A', 'C']]
# 使用boolean类型打印
# df.A > 8 则输出
print "筛选A值大于8:\n", df[df.A > 8]
以下是上述代码的运行结果
D:\software\Anaconda2\python.exe D:/PycharmProjects/Learn/learn_panda/learn_pd3.py
df:
A B C D
2018-01-10 0 1 2 3
2018-01-11 4 5 6 7
2018-01-12 8 9 10 11
2018-01-13 12 13 14 15
2018-01-14 16 17 18 19
2018-01-15 20 21 22 23
df[['A', 'B']]:
A B
2018-01-10 0 1
2018-01-11 4 5
2018-01-12 8 9
2018-01-13 12 13
2018-01-14 16 17
2018-01-15 20 21
df.A:
2018-01-10 0
2018-01-11 4
2018-01-12 8
2018-01-13 12
2018-01-14 16
2018-01-15 20
Freq: D, Name: A, dtype: int32
df[0:3]:
A B C D
2018-01-10 0 1 2 3
2018-01-11 4 5 6 7
2018-01-12 8 9 10 11
df['20180111':'20180113']:
A B C D
2018-01-11 4 5 6 7
2018-01-12 8 9 10 11
2018-01-13 12 13 14 15
df.loc['20180111']:
A 4
B 5
C 6
D 7
Name: 2018-01-11 00:00:00, dtype: int32
df.loc[:, ['A', 'B']]:
A B
2018-01-10 0 1
2018-01-11 4 5
2018-01-12 8 9
2018-01-13 12 13
2018-01-14 16 17
2018-01-15 20 21
df.loc['20180111':'20180113', ['A', 'B']]:
A B
2018-01-11 4 5
2018-01-12 8 9
2018-01-13 12 13
打印第三行的数据:
A 8
B 9
C 10
D 11
Name: 2018-01-12 00:00:00, dtype: int32
打印第三行中的第一个:
8
筛选地4和5列,2和3行:
B C
2018-01-13 13 14
2018-01-14 17 18
筛选1,3,5行,1:3列:
B C
2018-01-11 5 6
2018-01-13 13 14
2018-01-15 21 22
筛选2和3行,A和C列:
A C
2018-01-11 4 6
2018-01-12 8 10
筛选A值大于8:
A B C D
2018-01-13 12 13 14 15
2018-01-14 16 17 18 19
2018-01-15 20 21 22 23
Process finished with exit code 0