Pandas使用教程
Pandas
Pandas是基于Numpy构建的 让Numpy为中心的应用变得更加简单
要使用pandas 首先要了解他主要两个数据结构 Series和DataFrame
import pandas as pd
import numpy as np
s = pd.Series([1,3,6,np.nan,44,1])
print(s)
"""
0 1.0
1 3.0
2 6.0
3 NaN
4 44.0
5 1.0
dtype: float64
"""
Series的字符串表现形式为:索引在左边,值在右边。由于我们没有为数据指定索
引。于是会自动创建一个0到N-1(N为长度)的整数型索引。
>>> d = pd.Series(['人','生','苦','短','我','用','Python'])
>>> d
0 人
1 生
2 苦
3 短
4 我
5 用
6 Python
dtype: object
DataFrame
DataFrame是一个表格型的数据结构,它包含有一组有序的列,每列可以是不同的值类型(数值,字符串,布尔值等)。DataFrame既有行索引也有列索引, 它可以被看做由Series组成的大字典。
dataes = pd.date_range('20190506',periods=6)
>>> dataes
DatetimeIndex(['2019-05-06', '2019-05-07', '2019-05-08', '2019-05-09',
'2019-05-10', '2019-05-11'],
dtype='datetime64[ns]', freq='D')
>>> df = pd.DataFrame(np.random.randn(6,4),index=dataes,columns=['a','b','c','d'])
>>> df
a b c d
2019-05-06 -0.420496 0.180143 -0.112485 -1.582743
2019-05-07 1.093316 1.135457 -0.733968 1.506826
2019-05-08 0.656655 0.250544 -0.041902 0.447925
2019-05-09 -1.449409 -1.171222 1.304818 -1.864983
2019-05-10 -1.071781 -0.753814 -1.332882 -1.283546
2019-05-11 0.219359 -0.587689 1.128807 1.139987
具有行索引和列索引
>>> df['a']
2019-05-06 -0.425716
2019-05-07 -0.065539
2019-05-08 -0.089707
2019-05-09 -0.201775
2019-05-10 -0.473085
2019-05-11 0.846737
Freq: D, Name: a, dtype: float64
>>> df['a']['2019-05-06']
-0.4257161907860296
如果创建一组没有给定标签的数据 会采取默认的从0开始index
df1 = pd.DataFrame(np.arange(12).reshape((3,4)))
print(df1)
"""
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
"""
这种方法能对每一列的数据进行特殊对待. 如果想要查看数据中的类型, 我们可以用 dtype 这个属性: print(df2.dtypes)
查看队列的序号 df2.index
每种数据的名称 df2.dolumns
只看df2的值 df2.values
对数据的一些处理 df2.describe()
翻转数据 df2.T
对数据的index进行排序输出 df2.sort_index(axis=1, ascending=False)
对数据的值排序输出df2.sort_values(by=’B’) (按照B的值对df2进行排序)
可以根据位置设置loc和iloc来改变值
df.iloc[2,2] = 1111
df.loc['20130101','B'] = 2222
"""
A B C D
2013-01-01 0 2222 2 3
2013-01-02 4 5 6 7
2013-01-03 8 9 1111 11
2013-01-04 12 13 14 15
2013-01-05 16 17 18 19
2013-01-06 20 21 22 23
"""
根据条件设置
df.B[df.A>4] = 0 #根据A中的值来更改B中的数据
"""
A B C D
2013-01-01 0 2222 2 3
2013-01-02 4 5 6 7
2013-01-03 8 0 1111 11
2013-01-04 12 0 14 15
2013-01-05 16 0 18 19
2013-01-06 20 0 22 23
"""
根据行或者列进行设置
df['F'] = np.nan
"""
A B C D F
2013-01-01 0 2222 2 3 NaN
2013-01-02 4 5 6 7 NaN
2013-01-03 8 0 1111 11 NaN
2013-01-04 12 0 14 15 NaN
2013-01-05 16 0 18 19 NaN
2013-01-06 20 0 22 23 NaN
"""
添加数据
df['E'] = pd.Series([1,2,3,4,5,6], index=pd.date_range('20130101',periods=6))
"""
A B C D F E
2013-01-01 0 2222 2 3 NaN 1
2013-01-02 4 5 6 7 NaN 2
2013-01-03 8 0 1111 11 NaN 3
2013-01-04 12 0 14 15 NaN 4
2013-01-05 16 0 18 19 NaN 5
2013-01-06 20 0 22 23 NaN 6
"""
np.nan 代表的是位置数据为空
对于数据为空的数据可以进行以下的处理
如果想直接去掉有 NaN 的行或列, 可以使用 dropna
df.dropna(
axis=0, # 0: 对行进行操作; 1: 对列进行操作
how=’any’ # ‘any’: 只要存在 NaN 就 drop 掉; ‘all’: 必须全部是 NaN 才 drop
)
如果是将 NaN 的值用其他值代替, 比如代替成 0: df.fillna(value=0)
使用pd.isnull() 判断是否有缺失的数据nan 如果有那个位置变为True
没有则为False
检测在数据中是否存在 NaN, 如果存在就返回 True:
np.any(df.isnull()) == True
#True
pandas 导入导出数据
pandas可以读取和存取的资料格式有很多种,比如csv、excel、json、HTML、pickle、等…
读取csv
import pandas as pd #加载模块
#读取csv
data = pd.read_csv(‘student.csv’)
#打印出data
print(data)
data.to_pickle(‘student.pickle’) #将资料保存为pickle格式
pandas合并concat
处理多组数据的时候通常会用到数据的合并处理,concat是一种基本的合并方式,而且有很多参数可以调整,合并成你想要的数据形式
import pandas as pd
import numpy as np
#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d'])
df3 = pd.DataFrame(np.ones((3,4))*2, columns=['a','b','c','d'])
#concat纵向合并
res = pd.concat([df1, df2, df3], axis=0)
#打印结果
print(res)
# a b c d
# 0 0.0 0.0 0.0 0.0
# 1 0.0 0.0 0.0 0.0
# 2 0.0 0.0 0.0 0.0
# 0 1.0 1.0 1.0 1.0
# 1 1.0 1.0 1.0 1.0
# 2 1.0 1.0 1.0 1.0
# 0 2.0 2.0 2.0 2.0
# 1 2.0 2.0 2.0 2.0
# 2 2.0 2.0 2.0 2.0
#承上一个例子,并将index_ignore设定为True
res = pd.concat([df1, df2, df3], axis=0, ignore_index=True)
#打印结果
print(res)
# a b c d
# 0 0.0 0.0 0.0 0.0
# 1 0.0 0.0 0.0 0.0
# 2 0.0 0.0 0.0 0.0
# 3 1.0 1.0 1.0 1.0
# 4 1.0 1.0 1.0 1.0
# 5 1.0 1.0 1.0 1.0
# 6 2.0 2.0 2.0 2.0
# 7 2.0 2.0 2.0 2.0
# 8 2.0 2.0 2.0 2.0
join (合并方式)
是concat中 的一个参数 join=’outer’ 为预设值 按照column来纵向合并有相同的column上下合并。独自的column各自成列。没有值的位置以NaN填充
当 join=’inner’ 只有相同的column会进行合并,不同的会被抛弃
join_axes (按照axes合并)
import pandas as pd
import numpy as np
#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'], index=[1,2,3])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['b','c','d','e'], index=[2,3,4])
#依照`df1.index`进行横向合并
res = pd.concat([df1, df2], axis=1, join_axes=[df1.index])
#打印结果
print(res)
#a b c d b c d e
#1 0.0 0.0 0.0 0.0 NaN NaN NaN NaN
#2 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0
#3 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0
#移除join_axes,并打印结果
res = pd.concat([df1, df2], axis=1)
print(res)
#a b c d b c d e
#1 0.0 0.0 0.0 0.0 NaN NaN NaN NaN
#2 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0
#3 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0
#4 NaN NaN NaN NaN 1.0 1.0 1.0 1.0
append (添加数据)
append只有纵向合并,没有横向合并
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d'])#将df2合并到df1的下面,以及重置index,并打印出结果
res = df1.append(df2, ignore_index=True)
print(res)
#a b c d
#0 0.0 0.0 0.0 0.0
#1 0.0 0.0 0.0 0.0
#2 0.0 0.0 0.0 0.0
#3 1.0 1.0 1.0 1.0
#4 1.0 1.0 1.0 1.0
#5 1.0 1.0 1.0 1.0
pandas合并merge
pandas中的merge和concat类似,但主要是用于两组有key column的数据,统一索引的数据. 通常也被用在Database的处理当中.
res = pd.merge(left, right, on=’key’)
left和right 中都有key 的数据
当依据两组key合并的时候 有四种方法
how = [‘left’, ‘right’, ‘outer’, ‘inner’],预设值how=’inner’。
当以 how = ‘inner’时 只有left right中相同column以及对应的值相同时才会列出来。how = ‘outer’时 对应的值不同则会显示为NaN
为right 时则以right的值为标准
indicator=True会将合并的记录放在新的一列。
> df1 = pd.DataFrame({'col1':[0,1], 'col_left':['a','b']})
> df2 = pd.DataFrame({'col1':[1,2,2],'col_right':[2,2,2]})
> res = pd.merge(df1, df2, on='col1', how='outer', indicator=True)
> res
col1 col_left col_right _merge
0 0 a NaN left_only
1 1 b 2.0 both
2 2 NaN 2.0 right_only
3 2 NaN 2.0 right_only
根据index进行合并
import pandas as pd
#定义资料集并打印出
left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
'B': ['B0', 'B1', 'B2']},
index=['K0', 'K1', 'K2'])
right = pd.DataFrame({'C': ['C0', 'C2', 'C3'],
'D': ['D0', 'D2', 'D3']},
index=['K0', 'K2', 'K3'])
print(left)
#A B
#K0 A0 B0
#K1 A1 B1
#K2 A2 B2
print(right)
#C D
#K0 C0 D0
#K2 C2 D2
#K3 C3 D3
#依据左右资料集的index进行合并,how=’outer’,并打印出
res = pd.merge(left, right, left_index=True, right_index=True, how='outer')
print(res)
#A B C D
#K0 A0 B0 C0 D0
#K1 A1 B1 NaN NaN
#K2 A2 B2 C2 D2
#K3 NaN NaN C3 D3
当column 多个重复 时 受用suffixes来解决 可以来进行区别
import pandas as pd
#定义资料集
boys = pd.DataFrame({'k': ['K0', 'K1', 'K2'], 'age': [1, 2, 3]})
girls = pd.DataFrame({'k': ['K0', 'K0', 'K3'], 'age': [4, 5, 6]})
#使用suffixes解决overlapping的问题
res = pd.merge(boys, girls, on='k', suffixes=['_boy', '_girl'], how='inner')
print(res)
#age_boy k age_girl
#0 1 K0 4
#1 1 K0 5