pandas有两个主要的数据结构DataFrame和Series。DataFrame是一个类似数据库表的二维结构,Series是一个一维结构。对于pandas的一个简单直观的认识就是pandas基于这两个数据结构,提供了相关的数据操作和绘图函数。用这些函数可以实现从文件加载数据、选择数据、数据清洗、添加、插入、删除、分组和转换等操作。
1. 加载数据
import pandas as pd
filename = 'data/datasets-uci-iris.csv'
iris = pd.read_csv(filename, sep=',', decimal='.', header=None,
names=['sepal_length', 'sepal_width',
'petal_length', 'petal_width','target'])
iris.head()
Out[10]:
sepal_length sepal_width petal_length petal_width target
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa
iris.columns
Out[13]:
Index([u'sepal_length', u'sepal_width', u'petal_length', u'petal_width',
u'target'],
dtype='object')
2.选择数据列
类似sql中的select field01, fiedl02 from t1
Y = iris['target']
Y.head()
Out[20]:
0 Iris-setosa
1 Iris-setosa
2 Iris-setosa
3 Iris-setosa
4 Iris-setosa
Name: target, dtype: object
X = iris[['sepal_length', 'sepal_width']]
X.head()
Out[21]:
sepal_length sepal_width
0 5.1 3.5
1 4.9 3.0
2 4.7 3.2
3 4.6 3.1
4 5.0 3.6
选择列后再选择行
import os
filename = 'data/datasets-uci-iris.csv'
filename = os.getcwd() + "/essentials/" + filename
iris = pd.read_csv(filename, sep=',', decimal='.', header=None,
names=['sepal_length', 'sepal_width',
'petal_length', 'petal_width','target'])
iris['target'][10]
Out[9]:
'Iris-setosa'
iris['target'][10:12]
Out[10]: