Pandas 的基本数据结构

242 阅读5分钟

「这是我参与11月更文挑战的第 24 天,活动详情查看:2021最后一次更文挑战

Pandas是什么?

Pandas是数据分析的核心工具包,基于Numpy创建,为数据分析而存在。

  • 一维数组Series + 二维数组Dataframe
  • 可直接读取数据并做处理(高效简单)
  • 兼容各种数据库
  • 支持各种分析方法

Pandas基本数据结构-Series的基本概念

先举个栗子:

ar = np.random.rand(5)
s = pd.Series(ar)
print(ar)
print(s,type(s))
>>>
[0.1206055  0.83147658 0.88649587 0.2162775  0.31466148]
0    0.120605
1    0.831477
2    0.886496
3    0.216277
4    0.314661
dtype: float64 <class 'pandas.core.series.Series'>

在这里可以看到这里的Series相比与之前学习的ndarray是一个自带索引index的数组 = 一维的数组 + 对应的索引,当pd.Series单单只看values时就是一个ndarray。

在具体操作方面,Series和ndarray基本相似,包括索引切片的操作差别并不大。

Pandas基本数据结构-Series的创建方法

字典创建Series
# 字典创建Series
dic = {'a':1, 'b':2, 'c':3}
s = pd.Series(dic)
print(s)
数组创建Series
# 数组创建Series
arr = np.random.rand(5)*200
s = pd.Series(arr)
print(arr)
print(s,type(s))
Series的参数设置

我们可以通过指定Series的index以及dtype参数创建符合我们要求的Series。

# Series的参数设置
s = pd.Series(arr,index=list('abcde'),dtype=np.int,name=test)
print(s)
# index参数:设置index,长度保持一致
# dtype参数:设置数值类型
# 那么参数:设置名称
通过标量创建Series
s = pd.Series(arr,index=np.arange(5))
print(s)

Pandas基本数据结构-Series的索引

位置下标索引

位置下标从0开始,索引结果为numpy.float格式并且可以通过float()格式转换为float格式,且位置下标索引是没有负数的。

s = pd.Series(np.random.rand(5))
print(s)
print(s[0],type(s[0]),s[0].dtype)
print(float(s[0]),type(float(s[0])))
>>>
0    0.495361
1    0.152195
2    0.217591
3    0.748394
4    0.093389
dtype: float64
0.49536125725281055 <class 'numpy.float64'> float64
0.49536125725281055 <class 'float'>
标签索引
# 标签索引
s = pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
print(s)
print(s['a'],type(s['a']),s['a'].dtype)

# 如果需要选择多个标签的值,用[[]]来表示(相当于[]中包含一个列表)
# 多标签索引结果是新的数组
sci = s[['a','b','e']]
print(sci,type(sci))
>>>
a    0.714630
b    0.213957
c    0.172188
d    0.972158
e    0.875175
dtype: float64
0.714630383451 <class 'numpy.float64'> float64
a    0.714630
b    0.213957
e    0.875175
dtype: float64 <class 'pandas.core.series.Series'>
切片索引
s1 = pd.Series(np.random.rand(5))
s2 = pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
print(s1[1:4],s1[4])
print(s2['a':'c'],s2['c'])
print(s2[0:3],s2[3])
print('-----')
# 注意:用index做切片是末端包含

print(s2[:-1])
print(s2[::2])
# 下标索引做切片,和list写法一样
>>>
1    0.865967
2    0.114500
3    0.369301
dtype: float64 0.411702342342
a    0.717378
b    0.642561
c    0.391091
dtype: float64 0.39109096261
a    0.717378
b    0.642561
c    0.391091
dtype: float64 0.998978363818
-----
a    0.717378
b    0.642561
c    0.391091
d    0.998978
dtype: float64
a    0.717378
c    0.391091
e    0.957639
dtype: float64
布尔型索引

数组做判断之后,返回的是一个由布尔值组成的新的数组

.isnull() / .notnull() 判断是否为空值 (None代表空值,NaN代表有问题的数值,两个都会识别为空值)

布尔型索引方法:用[判断条件]表示,其中判断条件可以是 一个语句,或者是 一个布尔型数组!



s = pd.Series(np.random.rand(3)*100)
s[4] = None  # 添加一个空值
print(s)
bs1 = s > 50
bs2 = s.isnull()
bs3 = s.notnull()
print(bs1, type(bs1), bs1.dtype)
print(bs2, type(bs2), bs2.dtype)
print(bs3, type(bs3), bs3.dtype)
print('-----')
print(s[s > 50])
print(s[bs3])
>>>
0    2.03802
1    40.3989
2    25.2001
4       None
dtype: object
0    False
1    False
2    False
4    False
dtype: bool <class 'pandas.core.series.Series'> bool
0    False
1    False
2    False
4     True
dtype: bool <class 'pandas.core.series.Series'> bool
0     True
1     True
2     True
4    False
dtype: bool <class 'pandas.core.series.Series'> bool
-----
Series([], dtype: object)
0    2.03802
1    40.3989
2    25.2001
dtype: object

Pandas数据结构Series-基本技巧

数据查看
#查看前五的数据
s = pd.Series(np.random.rand(15))
print(s.head())   #默认查看数据前五条
# 查看后5条数据
print(s.tail())   #默认查看数据的后五条
# 查看前10条数据
print(s.head(10))
重新索引

重新索引的作用是根据新的索引重新排序,若新的索引不存在则引入缺失值。

# .reindex将会根据索引重新排序,如果当前索引不存在,则引入缺失值
s = pd.Series(np.random.rand(5),index=['a','b','c','d','e'])
print(s)
# 将索引值修改为['c','d','a','f']
s1 =  s.reindex(['c','d','a','f'])
print(s1)
>>>
a    0.972218
b    0.820531
c    0.940448
d    0.009572
e    0.462811
dtype: float64
c    0.940448
d    0.009572
a    0.972218
f         NaN
dtype: float64

如果不想引入缺失值可以使用fill_value指定不存在的索引值为0或其他值

s2 = s.reindex(['c','d','a','f','aaaaa'], fill_value=0)
print(s2)
>>>
c        0.940448
d        0.009572
a        0.972218
f        0.000000
aaaaa    0.000000
dtype: float64
数据对齐

对齐两列数据,当数据索引不同时存在需要对齐的Series的时,数据值以缺失值填充。

# Series 和 ndarray 之间的主要区别是,Series 上的操作会根据标签自动对齐
# index顺序不会影响数值计算,以标签来计算
# 空值和任何值计算结果扔为空值
s1 = pd.Series(np.random.rand(3),index=['jack','marry','tom'])
s2 = pd.Series(np.random.rand(3),index=['wang','jack','marry'])
print(s1+s2)
>>>
jack     1.261341
marry    0.806095
tom           NaN
wang          NaN
dtype: float64
删除

使用.drop删除元素的时候,默认返回的是一个副本(inplace=False)

s = pd.Series(np.random.rand(5), index = list('ngjur'))
print(s)
s1 = s.drop('n')
s2 = s.drop(['g','j'])
print(s1)
print(s2)
print(s)
>>>
n    0.876587
g    0.594053
j    0.628232
u    0.360634
r    0.454483
dtype: float64
g    0.594053
j    0.628232
u    0.360634
r    0.454483
dtype: float64
n    0.876587
u    0.360634
r    0.454483
dtype: float64
n    0.876587
g    0.594053
j    0.628232
u    0.360634
r    0.454483
dtype: float64
添加

方法一:直接通过下标索引/标签index添加值

s1 = pd.Series(np.random.rand(5))
s2 = pd.Series(np.random.rand(5), index = list('ngjur'))
print(s1)
print(s2)
s1[5] = 100
s2['a'] = 100
print(s1)
print(s2)
>>>
0    0.516447
1    0.699382
2    0.469513
3    0.589821
4    0.402188
dtype: float64
n    0.615641
g    0.451192
j    0.022328
u    0.977568
r    0.902041
dtype: float64
0      0.516447
1      0.699382
2      0.469513
3      0.589821
4      0.402188
5    100.000000
dtype: float64
n      0.615641
g      0.451192
j      0.022328
u      0.977568
r      0.902041
a    100.000000
dtype: float64

方法二:使用.append()方法添加,可以直接添加一个数组,且生成一个新的数组,不改变之前的数组。

s3 = s1.append(s2)
print(s3)
print(s1)
>>>
0      0.238541
1      0.843671
2      0.452739
3      0.312212
4      0.878904
5    100.000000
n      0.135774
g      0.530755
j      0.886315
u      0.512223
r      0.551555
a    100.000000
dtype: float64
0      0.238541
1      0.843671
2      0.452739
3      0.312212
4      0.878904
5    100.000000
dtype: float64
修改

series可以通过索引直接修改,类似序列

s = pd.Series(np.random.rand(3), index = ['a','b','c'])
print(s)
s['a'] = 100
s[['b','c']] = 200
print(s)
>>>
a    0.873604
b    0.244707
c    0.888685
dtype: float64
a    100.0
b    200.0
c    200.0
dtype: float64