一、背景知识
Pandas是为了解决数据分析任务而创建的,纳入了大量的库和标准数据模型,提供了高效地操作大型数据集所需的工具。
对于Pandas包,在Python中常见的导入方法如下:
from pandas import Series,DataFrame
import pandas as pd
Pandas中的数据结构 :
- Series: 一维数组,类似于Python中的基本数据结构list,区别是Series只允许存储相同的数据类型,这样可以更有效的使用内存,提高运算效率。就像数据库中的列数据。
如下例子:
In :obj=Series([4,7,-5,3])
In :obj
Out:
0 4
1 7
2 -5
3 3
Series的交互式显示的字符串表示形式是索引在左边,值在右边
我们还可以自己创建索引,这就类似字典了
In :obj2=Series([4,7,-5,3],index=['d','b','a','c'])
In :obj2
Out:
d 4
b 7
a -5
c 3
如果你有一些数据在一个Python字典中,你可以通过传递字典来从这些数据创建一个Series,只传递一个字典的时候,结果Series中的索引将是排序后的字典的键
In [7]:sdata={'Ohio':35000,'Texas':71000,'Oregon':16000,'Utah':5000}
In [8]:obj3=Series(sdata)
In [9]:obj3
Out[9]:
Ohio 35000
Texas 71000
Oregon 16000
Utah 5000
- DataFrame: 一个表格型的数据结构,是以一个或多个二维块存放的数据表格(层次化索引),DataFrame既有行索引还有列索引,它有一组有序的列,每列既可以是不同类型(数值、字符串、布尔型)的数据,或者可以看做由Series组成的字典。
DataFrame创建(开头是列名,[ ]里面是每列的内容)
dictionary = {'state':['0hio','0hio','0hio','Nevada','Nevada'],
'year':[2000,2001,2002,2001,2002],
'pop':[1.5,1.7,3.6,2.4,2.9]}
frame = DataFrame(dictionary)
修改行名
frame=DataFrame(dictionary,index=['one','two','three','four','five'])
添加新列
frame['add']=[0,0,0,0,0] '列名'=[值]
- Panel:三维的数组,可以理解为DataFrame的容器。
二、利用Pandas导入csv格式数据
读取CSV
# 如果数据集中有中文的话,最好在里面加上 encoding = 'gbk' ,以避免乱码问题。后面的导出数据的时候也一样。
df = pd.read_csv('uk_rain_2014.csv', header=0, encoding = 'gbk')
# header 关键字告诉 Pandas 哪些是数据的列名。如果没有列名的话就将它设定为 None
数据导入pandas之后,我们该怎么查看数据呢?
# 查看前五行
df.head(5)
# 查看后五行
df.tail(5)
# 查看总行数
len(df)
修改列名
df.columns = ['学号','班级','性别','年龄', '专业', '手机号码', '邮箱']
三、排序
- Series
# 初始化
In: obj = Series(range(4), index=['d','a','b','c'])
# 按索引排序
In: obj.sort_index()
Out:
a 1
b 2
c 3
d 0
# 按值排序
In: obj.sort() 或 obj.order()
In: obj
Out:
d 0
a 1
b 2
c 3
- DataFrame
# 初始化
In: frame = DataFrame(np.arange(8).reshape((2,4)),index=['three', 'one'],columns=['d','a','b','c'])
In: frame
Out:
d a b c
three 0 1 2 3
one 4 5 6 7
# 按索引排序(即第一列)
In: frame.sort_index() 或frame.sort()
Out:
d a b c
one 4 5 6 7
three 0 1 2 3
# 按行(第一行)排序
In[89]: frame.sort_index(axis=1, ascending=False)
Out[89]:
d c b a
three 0 3 2 1
one 4 7 6 5
# 按值排序
In[95]: frame = DataFrame({'b':[4, 7, -3, 2], 'a':[0, 1, 0, 1]})
In[97]: frame.sort_values(by='b')
Out[97]:
a b
2 0 -3
3 1 2
0 0 4
1 1 7
四、删除指定轴上的项
即删除 Series 的元素或 DataFrame 的某一行(列)的意思,我们可以通过对象的 drop(labels, axis=0) 方法实现此功能。
- 删除Series的一个元素:
In: ser = Series([4.5,7.2,-5.3,3.6], index=['d','b','a','c'])
In: ser.drop('c')
Out:
d 4.5
b 7.2
a -5.3
- 删除DataFrame的行或列(axis=0代表往跨行(down),而axis=1代表跨列(across))
In[17]: df = DataFrame(np.arange(9).reshape(3,3), index=['a','c','d'], columns=['oh','te','ca'])
In[18]: df
Out[18]:
oh te ca
a 0 1 2
c 3 4 5
d 6 7 8
In[19]: df.drop('a')
Out[19]:
oh te ca
c 3 4 5
d 6 7 8
In[20]: df.drop(['oh','te'],axis=1)
Out[20]:
ca
a 2
c 5
d 8
补充:
下图代表在DataFrame当中axis为0和1时分别代表的含义:
五、去重
duplicated()
DataFrame的duplicated方法返回一个布尔型Series,表示各行是否是重复行。具体用法如下:
In[1]: df = DataFrame({'k1':['one']*3 + ['two']*4, 'k2':[1,1,2,3,3,4,4]})
In[2]: df
Out[2]:
k1 k2
0 one 1
1 one 1
2 one 2
3 two 3
4 two 3
5 two 4
6 two 4
In[3]: df.duplicated()
Out[3]:
0 False
1 True
2 False
3 False
4 True
5 False
6 True
dtype: bool
drop_duplicates()
drop_duplicates() 用于去除重复的行数,具体用法如下:
In[4]: df.drop_duplicates()
Out[4]:
k1 k2
0 one 1
2 one 2
3 two 3
5 two 4
六、数据重塑
将Series转化成DataFrame:
In[1]:data = Series(np.random.randn(10), index = [['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd' ],[1,2,3,1,2,3,1,2,2,3]])
In[2]:data
Out[2]:
a 1 0.169239
2 0.689271
3 0.879309
b 1 -0.699176
2 0.260446
3 -0.321751
c 1 0.893105
2 0.757505
d 2 -1.223344
3 -0.802812
in[5]:data.unstack()
Out[5]:
1 2 3
a 0.169239 0.689271 0.879309
b -0.699176 0.260446 -0.321751
c 0.893105 0.757505 NaN
d NaN -1.223344 -0.802812