Pandas是一个强大的分析结构化数据的工具集,基于NumPy构建,提供了高级数据结构和数据操作工具,它是使Python成为强大而高效的数据分析环境的重要因素之一
1、pandas的数据结构
(1)Series
Series是一种类似于一维数组的对象,组成:
一组数据(各种NumPy数据类型)
一组与之对应的索引(数据标签)
索引(index)在左,数据(values)在右
索引是自动创建的
a 通过list构建Series
import pandas as pd
ser_obj = pd.Series(range(1, 5))
print(ser_obj)
print(ser_obj.head(3)) # 打印前三行数据
print(type(ser_obj)) # 打印数据类型
0 1
1 2
2 3
3 4
dtype: int64
0 1
1 2
2 3
dtype: int64
<class 'pandas.core.series.Series'>
b 用字典创建Series
dic = {1000: "hello", 2000: "world", 3000: "!"}
ser_obj = pd.Series(dic)
print(ser_obj)
1000 hello
2000 world
3000 !
dtype: object
(2)DataFrame
一个表格型的数据结构,它含有一组有序的列,每列可以是不同类型的值。DataFrame既有行索引也有列索引,数据是以二维结构存放的。
类似多维数组/表格数据 (如,excel, R中的data.frame)
每列数据可以是不同的类型
索引包括列索引和行索引
a 通过ndarray创建DataFrame
import numpy as np
arr_obj = np.random.rand(3, 4)
df_obj = pd.DataFrame(arr_obj)
print(df_obj)
print(df_obj.head(2)) # 看前两行
0 1 2 3
0 0.857111 0.125885 0.080517 0.279508
1 0.046565 0.500215 0.334141 0.048163
2 0.741607 0.503988 0.526194 0.885707
0 1 2 3
0 0.857111 0.125885 0.080517 0.279508
1 0.046565 0.500215 0.334141 0.048163
b 通过dict创建DataFrame
dic = {
"A": 1,
"B": pd.Timestamp("20171212"),
"C": pd.Series(range(10,14), dtype="float64"),
"D": ["python", "java", "c++", "c"]}
df_obj = pd.DataFrame(dic)
print(df_obj)
# DataFrame数据访问
# 通过索引,先列后行
print(df_obj['D'][0])
# 查找指定元素,先找列,在找行
print(df_obj.D[2])
A B C D
0 1 2017-12-12 10.0 python
1 1 2017-12-12 11.0 java
2 1 2017-12-12 12.0 c++
3 1 2017-12-12 13.0 c
python
c++
2、索引
(1)Series的索引操作
# Series index 指定行索引名 不指定索引的话,默认从0开始
ser_obj = pd.Series(range(5), index=['a', 'b', 'c', 'd', 'e'])
print(ser_obj.head())
# 行索引 ser_obj[‘label’], ser_obj[pos]
print(ser_obj['b'])
print(ser_obj[2])
# 切片索引 ser_obj[2:4], ser_obj[‘label1’: ’label3’]
print(ser_obj[1:3])
# print(ser_obj.iloc[1:3])
print(ser_obj['b':'d'])
# print(ser_obj.loc['b':'d'])
# 不连续索引 ser_obj[[‘label1’, ’label2’, ‘label3’]]
print(ser_obj[[0, 2, 4]])
print(ser_obj[['a', 'e']])
# 布尔索引
ser_bool = ser_obj > 2
print(ser_bool)
print(ser_obj[ser_bool])
print(ser_obj[ser_obj > 2])
a 0
b 1
c 2
d 3
e 4
dtype: int64
1
2
b 1
c 2
dtype: int64
b 1
c 2
d 3
dtype: int64
a 0
c 2
e 4
dtype: int64
a 0
e 4
dtype: int64
a False
b False
c False
d True
e True
dtype: bool
d 3
e 4
dtype: int64
d 3
e 4
dtype: int64
(2)、DataFrame的索引操作
# 指定列索引
df_obj = pd.DataFrame(np.random.randn(5, 4), columns=['a', 'b', 'c', 'd'])
print(df_obj.head())
# print(df_obj)
print(df_obj['a'])
print(df_obj[['a', 'c']])
print(df_obj.head(2))
# 第一个参数索引行,第二个参数是列
print(df_obj.loc[0:2, 'a'])
print(df_obj.loc[1:3, ['b', 'c']])
print(df_obj.loc[1:3, 'b':'d'])
a b c d
0 1.699547 0.167901 -0.553991 1.260153
1 -1.330424 1.967958 1.575544 0.903244
2 -1.653570 1.088742 0.263336 0.292219
3 -0.993177 -0.605804 -0.360061 -1.665650
4 0.286143 -0.151411 0.074310 0.830517
0 1.699547
1 -1.330424
2 -1.653570
3 -0.993177
4 0.286143
Name: a, dtype: float64
a c
0 1.699547 -0.553991
1 -1.330424 1.575544
2 -1.653570 0.263336
3 -0.993177 -0.360061
4 0.286143 0.074310
a b c d
0 1.699547 0.167901 -0.553991 1.260153
1 -1.330424 1.967958 1.575544 0.903244
0 1.699547
1 -1.330424
2 -1.653570
Name: a, dtype: float64
b c
1 1.967958 1.575544
2 1.088742 0.263336
3 -0.605804 -0.360061
b c d
1 1.967958 1.575544 0.903244
2 1.088742 0.263336 0.292219
3 -0.605804 -0.360061 -1.665650
(3)
ser_obj = pd.Series(range(5), index=['a', 'b', 'c', 'd', 'e'])
df_obj = pd.DataFrame(np.random.randn(5, 4), columns=['a', 'b', 'c', 'd'])
print(df_obj)
# 和ser_obj[1:3] ser_obj.iloc[1:3]
print(ser_obj.ix[1:3])
print(ser_obj.ix['b':'c'])
print(df_obj.loc[0:2, 'a'])
print(df_obj.ix[0:2, 0])
a b c d
0 0.923516 2.047034 -1.857026 -0.119109
1 -0.174115 -0.648059 0.740559 0.991716
2 2.261348 0.154458 0.756239 0.961582
3 -0.661376 1.029583 -0.367033 -0.413477
4 -0.474945 0.953137 0.487682 -0.475225
b 1
c 2
dtype: int64
b 1
c 2
dtype: int64
0 0.923516
1 -0.174115
2 2.261348
Name: a, dtype: float64
0 0.923516
1 -0.174115
2 2.261348
Name: a, dtype: float64
3、pandas常用的统计函数
4、分组
在分组的基础上,对分组对象调用方法进行运算;分组运算只能作用与数据部分,非数据部分不参与运算
dict_obj = {'key1': ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'a'],
'key2': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'data1': np.random.randn(8),
'data2': np.random.randn(8)}
df_obj = pd.DataFrame(dict_obj)
print(df_obj)
print('#'*40)
# 分组操作,如果对整个数据集进行分组,groupby参数直接指定列名即可
grouped = df_obj.groupby("key2")
print(grouped.sum()) # one two three 对应列的和
print('#'*40)
grouped1 = df_obj.groupby('key1')
print(grouped1.mean()) # a b对应列的和
print('#'*40)
print(grouped1.size()) # a的个数 b的个数
key1 key2 data1 data2
0 a one 0.890465 2.023672
1 b one -1.118138 1.460645
2 a two -0.145798 -2.102257
3 b three 0.642693 -1.148929
4 a two 0.250901 1.336286
5 b two 1.484032 0.016922
6 a one 0.075970 -0.298883
7 a three 0.128039 0.127414
########################################
data1 data2
key2
one -0.151703 3.185434
three 0.770732 -1.021515
two 1.589135 -0.749049
########################################
data1 data2
key1
a 0.239915 0.217246
b 0.336196 0.109546
########################################
key1
a 5
b 3
dtype: int64
5、排序
分为按索引排序和按值排序
(1). 索引排序
sort_index(),排序默认使用升序排序,ascending=False 为降序排序
# Series
ser_obj2 = pd.Series(range(10, 15), index=np.random.randint(5, size=5))
print(ser_obj2)
print(ser_obj2.sort_index()) # 正序排列
print(ser_obj2.sort_index(ascending=False)) # 降序排序
1 10
1 11
4 12
2 13
0 14
dtype: int64
0 14
1 10
1 11
2 13
4 12
dtype: int64
4 12
2 13
1 10
1 11
0 14
dtype: int64
ser_obj2 = pd.Series(range(10, 15), index=np.random.randint(5, size=5))
print(ser_obj2)
print(ser_obj2.sort_index()) # 正序排列
print(ser_obj2.sort_index(ascending=False)) # 降序排序
# DataFrame
# 对DataFrame操作时注意轴方向,默认列,axis = 1 为行
df_obj = pd.DataFrame(np.random.randn(3, 5),
index=np.random.randint(3, size=3),
columns=np.random.randint(5, size=5))
print(df_obj)
df_obj_sort = df_obj.sort_index(axis=1, ascending=False)
print(df_obj_sort)
2 3 3 0 1
1 -0.010198 -1.482997 -0.406972 -0.189502 1.502781
2 0.578446 -0.351943 -0.630512 -0.190805 1.810662
1 0.346445 0.163318 0.728293 0.155396 0.580143
3 3 2 1 0
1 -1.482997 -0.406972 -0.010198 1.502781 -0.189502
2 -0.351943 -0.630512 0.578446 1.810662 -0.190805
1 0.163318 0.728293 0.346445 0.580143 0.155396
(2)按值排序
sort_values(by='column name') 根据某个唯一的列名进行排序,如果有其他相同列名则报错
# Series
ser_obj = pd.Series(np.random.randint(10, 20, size=10))
print(ser_obj)
print(ser_obj.sort_values()) # 默认升序
print(ser_obj.sort_values(ascending=False)) # 降序
0 14
1 14
2 13
3 11
4 12
5 10
6 12
7 17
8 15
9 18
dtype: int32
5 10
3 11
4 12
6 12
2 13
0 14
1 14
8 15
7 17
9 18
dtype: int32
9 18
7 17
8 15
1 14
0 14
2 13
6 12
4 12
3 11
5 10
dtype: int32
df4 = pd.DataFrame(np.random.randn(3, 5), index=np.random.randint(3, size=3), columns=np.random.randint(5, size=5))
print(df4)
print(df4.sort_values(by=3)) # 第三列 从小到大排列
print(df4.sort_values(by=1, axis=1)) # 第一行从小到大排列
2 1 3 1 4
1 1.383771 2.197203 1.455859 -0.776635 1.690965
0 1.188787 -0.732008 -2.523198 -0.468777 -0.711352
0 -0.017181 -0.490806 1.035051 -1.276688 -1.298208
2 1 3 1 4
0 1.188787 -0.732008 -2.523198 -0.468777 -0.711352
0 -0.017181 -0.490806 1.035051 -1.276688 -1.298208
1 1.383771 2.197203 1.455859 -0.776635 1.690965
1 2 3 4 1
1 -0.776635 1.383771 1.455859 1.690965 2.197203
0 -0.468777 1.188787 -2.523198 -0.711352 -0.732008
0 -1.276688 -0.017181 1.035051 -1.298208 -0.490806