0.摘要
Pandas相当于是Numpy的升级版本。在numpy中,核心的数据类型为ndarray;而在Pandas中,核心的数据核心Series和DataFrame。本文主要介绍pandas库中的DataFrame类型。
1.DataFrame类型简介
DataFrame主要由三部分构成:data,index和columns。与Series类型相比,多了一个columns部分。
可以看出,DataFrame相当于是Series类型的三维拓展。
如果columns只有一列,则DataFrame就是一种特殊的Series。
2.DataFrame类型的创建
DataFrame的创建方式主要有三种:
方式一:使用二维数组创建
import pandas as pd
import numpy as np
n = np.arange(20, dtype=float).reshape(5,4)
frame1 = pd.DataFrame(n)
print(frame1)
由于在创建过程中并没有指定index和columns,因此,pandas使用了默认的index和columns,即以0为起点的数组。
方式二:指定index和columns
import pandas as pd
import numpy as np
n = np.arange(20, dtype=float).reshape(5,4)
index = ['index1', 'index2', 'index3', 'index4', 'index5']
columns = ['column1', 'column2', 'column3', 'column4']
frame2 = pd.DataFrame(data=n, index=index, columns=columns)
print(frame2)
方式三:使用字典
import pandas as pd
import numpy as np
n = np.arange(20, dtype=float).reshape(5,4)
d = {'column1': [ 0., 4., 8., 12., 16.], 'column2': [ 1., 5., 9., 13., 17.], 'column3': [ 2., 6., 10., 14., 18.], 'column4': [ 3., 7., 11., 15., 19.]}
index = ['index1', 'index2', 'index3', 'index4', 'index5']
frame3 = pd.DataFrame(data=d, index=index)
print(frame3)
3.DataFrame类型的访问
DataFrame的访问方法有五种:
方式一:属性访问
print(frame3.index)
print(frame3.columns)
print(frame3.values)
方式二:访问某一列
print(frame3['column1']) # 访问第一列
print("========================")
print(frame3.column1) # 访问第一列
print("========================")
print(frame3[['column1', 'column2']]) # 访问第一列和第二列
方式三:访问某一行
print(frame3[0:1]) # 访问第一行
print("==========================")
print(frame3[1:3]) # 访问第二行到第三行
方式四:访问某个元素
访问单个元素:
访问元素的方式为:DataFrame[columns][index]。注意顺序,columns在前,index在后。
print(frame3['column2']['index1'])
访问某一区域元素:
使用loc方法访问:
print(frame3.loc[:, ['column1', 'column2']]) # 访问所有行的第一列和第二列元素
print("=============================")
print(frame3.loc[['index1', 'index2'], ['column1', 'column2']]) # 访问第二行到第三行中,第一列和第二列元素
使用iloc方法访问:
print(frame3.iloc[1:3, 0:2]) # 访问第二行到第三行中,第一列和第二列元素
print("=============================")
print(frame3.iloc[[0,2], [1,3]]) # 访问第一行和第三行中,第二列和第四列元素
使用ix方法访问:
print(frame3.ix[1:3, ['column1', 'column2']]) # 访问第二行到第三行中,第一列和第二列元素
print("=============================")
print(frame3.ix[['index1', 'index3'], [1,3]]) # 访问第一行和第三行中,第二列和第四列元素
总结:loc方法只能通过具体的索引值进行访问,iloc方法只能通过数字位置下标进行访问,而ix方法既可以通过具体索引值访问,也可以通过数字位置下标访问。
方式五:借助DataFrame.value间接访问:
print(frame3.values[0,1])
方式六:设置筛选条件
print(frame3.ix[frame3.column1>10.,:]) # 访问第一列大于10.的所有行