import pandas as pd
from pandas import DataFrame,Series
import numpy as np
原始索引
原始索引就是类list的索引方式。
当索引对象是切片时就是行索引。
>>> df[1:3]
age animal priority visits
b 3.0 cat yes 3
c 0.5 snake no 2
>>> df[['age', 'animal']]
age animal
a 2.5 cat
b 3.0 cat
c 0.5 snake
d NaN dog
e 5.0 dog
f 2.0 cat
g 4.5 snake
h NaN cat
i 7.0 dog
j 3.0 dog
1、Series
Series是一种类似与一维数组的对象,由下面两个部分组成:
- values:一组数据(ndarray类型)
- index:相关的数据索引标签
1.Series的创建
两种创建方式:
(1) 由列表或numpy数组创建
默认索引为0到N-1的整数型索引
# 使用列表创建Series
Series(data=[1,2,3])
0 1
1 2
2 3
dtype: int64
- 还可以通过设置index参数指定索引
s = Series(data=[1,2,3],index=['a','b','c'])
s['c'] # 3
Series(data=np.random.randint(0,100,size=(3,)))
0 63
1 75
2 31
dtype: int32
Series(data=np.random.randint(0,100,size=(3,)),index=['a','b','x'])
a 4
b 18
x 40
dtype: int32
# 练习1:
使用多种方法创建以下Series,命名为s1:
语文 150
数学 150
英语 150
理综 300
s=Series(data=[150,150,150,300],index=['语文','数学','英语','理综'])
s
语文 150
数学 150
英语 150
理综 300
dtype: int64
2.Series的基本概念
1.可以使用s.head(),tail()分别查看前n个和后n个值
s.tail(1)
# 理综 300
# dtype: int64
2.对Series元素进行去重
s = Series(data=[1,2,2,2,3,3,11,1,4,5,5,46])
s.unique()
array([ 1, 2, 3, 11, 4, 5, 46], dtype=int64)
3.Series之间的运算
- 在运算中自动对齐不同索引的数据
- 如果索引不对应,则补NaN
当索引没有对应的值时,可能出现缺失数据显示NaN(not a number)的情况
# 使得两个Series进行相加
s1 = Series(data=[1,2,3,4],index=['a','b','c','d'])
s2 = Series(data=[1,2,3,4],index=['a','b','e','d'])
s = s1 + s2
s
a 2.0
b 4.0
c NaN
d 8.0
e NaN
dtype: float64
# 可以使用pd.isnull(),pd.notnull(),或s.isnull(),notnull()函数检测缺失数据
s.isnull()
a False
b False
c True
d False
e True
dtype: bool
s.notnull()
a True
b True
c False
d True
e False
dtype: bool
s
a 2.0
b 4.0
c NaN
d 8.0
e NaN
dtype: float64
s[[True,True,False,False,True]]
# 如果将布尔值作为Serrise的索引,则只保留True对应的元素值
a 2.0
b 4.0
e NaN
dtype: float64
s[s.notnull()]
a 2.0
b 4.0
d 8.0
dtype: float64
2、DataFrame
DataFrame是一个【表格型】的数据结构。DataFrame由按一定顺序排列的多列数据组成。设计初衷是将Series的使用场景从一维拓展到多维。DataFrame既有行索引,也有列索引。
- 行索引:index
- 列索引:columns
- 值:values
1.DataFrame的创建
最常用的方法是传递一个字典来创建。DataFrame以字典的键作为每一【列】的名称,以字典的值(一个数组)作为每一列。
此外,DataFrame会自动加上每一行的索引。
使用字典创建的DataFrame后,则columns参数将不可被使用。
同Series一样,若传入的列与字典的键不匹配,则相应的值为NaN
DataFrame(data=np.random.randint(60,100,size=(3,4)))
0 1 2 3
0 69 81 60 79
1 64 60 70 64
2 87 94 98 98
df = DataFrame(data=np.random.randint(60,100,size=(3,4)),index=['A','B','C'],columns=['a','b','c','d'])
df
a b c d
A 92 67 79 68
B 84 66 61 66
C 84 79 66 82
DataFrame属性:values、columns、index、shape
df.values
array([[92, 67, 79, 68],
[84, 66, 61, 66],
[84, 79, 66, 82]])
df.index
Index(['A', 'B', 'C'], dtype='object')
df.columns
Index(['a', 'b', 'c', 'd'], dtype='object')
df.shape
(3, 4)
练习4:
根据以下考试成绩表,创建一个DataFrame,命名为df:
张三 李四
语文 150 0
数学 150 0
英语 150 0
理综 300 0
================
dic = {
'张三':[150,150,150,150],
'李四':[0,0,0,0]
}
df = DataFrame(data=dic,index=['语文','数学','英语','理综'])
df
张三 李四
语文 150 0
数学 150 0
英语 150 0
理综 150 0
2.DataFrame的索引
(1) 对列进行索引
- 通过类似字典的方式 df['q']
- 通过属性的方式 df.q
可以将DataFrame的列获取为一个Series。返回的Series拥有原DataFrame相同的索引,且name属性也已经设置好了,就是相应的列名。
df = DataFrame(data=np.random.randint(60,100,size=(3,4)),index=['A','B','C'],columns=['a','b','c','d'])
# 查看原始数据
df
a b c d
A 75 71 92 98
B 79 93 86 80
C 78 87 94 91
#修改列索引
df.columns = ['a','c','b','d']
df
a c b d
A 75 71 92 98
B 79 93 86 80
C 78 87 94 91
#获取前两列
df[['a','c']]
a c
A 75 71
B 79 93
C 78 87
(2) 对行进行索引
- 使用.loc[]加index来进行行索引
- 使用.iloc[]加整数来进行行索引
同样返回一个Series,index为原来的columns。
# 查看原始数据
df
a c b d
A 75 71 92 98
B 79 93 86 80
C 78 87 94 91
df.iloc[0]
a 75
c 71
b 92
d 98
Name: A, dtype: int32
df.loc['A']
a 75
c 71
b 92
d 98
Name: A, dtype: int32
df.loc[['A','B']]
a c b d
A 75 71 92 98
B 79 93 86 80
(3) 对元素索引的方法
- 使用列索引
- 使用行索引(iloc[3,1] or loc['C','q']) 行索引在前,列索引在后
# 查看原始数据
df
a c b d
A 75 71 92 98
B 79 93 86 80
C 78 87 94 91
df.iloc[1,2]
86
df.loc[['B','C'],'b']
B 86
C 94
Name: b, dtype: int32
3.DataFrame的切片
【注意】 直接用中括号时:
索引表示的是列索引
切片表示的是行切片
# 查看原始数据
df
a c b d
A 75 71 92 98
B 79 93 86 80
C 78 87 94 91
df[0:2] # 切的是行
a c b d
A 75 71 92 98
B 79 93 86 80
在loc和iloc中使用切片(切列) : df.loc['B':'C','丙':'丁']
df.iloc[:,0:2] # 切列得iloc , loc
a c
A 75 71
B 79 93
C 78 87
# 索引
df['a']
A 75
B 79
C 78
Name: a, dtype: int32
总结:
索引:
取行:df.loc['A']
取列:df['a']
取元素:df.iloc[1,2]
切片:
切行:df[0:2]
切列:df.iloc[:,0:2]
4.DataFrame的运算
1) DataFrame之间的运算
同Series一样:
在运算中自动对齐不同索引的数据
如果索引不对应,则补NaN
# 查看原始数据
df
a c b d
A 75 71 92 98
B 79 93 86 80
C 78 87 94 91
df + df
a c b d
A 150 142 184 196
B 158 186 172 160
C 156 174 188 182