pandas 的数据对象 Series
概要
用pandas 有一段时间,很少去总结,这篇文章 简单总结一些 pandas 中series 的一些常用方法,如果有更多的需要,可以查询官方文档.
构造一个series 对象
import numpy as np
import pandas as pd
s = pd.Series(np.arange(6),index=list("ABCDEF"))
Series 有两部分组成
index 是索引对象,保存标签信息
values 是保存元素值的 ndarray数组
s
A 0
B 1
C 2
D 3
E 4
F 5
dtype: int64
s.index
Index(['A', 'B', 'C', 'D', 'E', 'F'], dtype='object')
s.values
array([0, 1, 2, 3, 4, 5])
series 可以通过 位置,或者标签信息 拿到数据,同时 也支持python中的切片操作。
1.通过位置来索引
s[0]
0
s[1]
1
s[3]
3
s[2:4]
C 2
D 3
dtype: int64
- 通过index 来取值
如果通过index 去取值,切边的话,两端都包含。这一点和 普通切片有点区别的.
s
A 0
B 1
C 2
D 3
E 4
F 5
dtype: int64
s['D']
3
s['B']
1
s['C':'E']
C 2
D 3
E 4
dtype: int64
dtype: int64
s['C':'F']
C 2
D 3
E 4
F 5
dtype: int64
s['C':'G']
C 2
D 3
E 4
F 5
dtype: int64
如果构造series没有指定index, 则自动生成 0到series长度-1 的Rangeindex
s2 = pd.Series([20,30,40,50])
s2
0 20
1 30
2 40
3 50
dtype: int64
s2.index
RangeIndex(start=0, stop=4, step=1)
s2.values
array([20, 30, 40, 50])
来说谈一下series的操作
1 排序操作
sort_values(self, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')
na_position : {‘first’ or ‘last’}, default ‘last’
inplace= False or True
sort_value 有几个参数
- ascending 是否升序 True or False
- inplace 是否 原地替换, 默认False ,返回一个series 不改变原来的值,如果设置为True 直接改变series 的值。
- na_position 空值的位置,放在前面还是后面,默认值是last,也可以是first
- kind 是选择什么排序算法,{‘quicksort’, ‘mergesort’ or ‘heapsort’} 默认是 quicksort
s = pd.Series([np.nan, 1, 3, 10,8,2, 5])
s = pd.Series([np.nan, 1, 3, 10, 5])
s = pd.Series([np.nan, 1, 3, 10, 5])
# 升序排序 默认
s.sort_values(ascending=True)
1 1.0
2 3.0
4 5.0
# 降序排序
s.sort_values(ascending=False)
# inplace 是否直接替换原来的series 的值 ,默认是False
# 重新构造一个 series
s = pd.Series([np.nan, 1, 3, 10,8,2, 5])
s = pd.Series([np.nan, 1, 3, 10,8,2, 5])
s
0 NaN
1 1.0
2 3.0
3 10.0
4 8.0
5 2.0
6 5.0
dtype: float64
s.sort_values(inplace=True)
s
1 1.0
5 2.0
2 3.0
6 5.0
4 8.0
3 10.0
0 NaN
dtype: float64
s = pd.Series([np.nan, 1, 3, 10,8,2, 5])
s.sort_values()
1 1.0
5 2.0
2 3.0
6 5.0
4 8.0
3 10.0
0 NaN
dtype: float64
s.sort_values(na_position='first')
0 NaN
1 1.0
5 2.0
2 3.0
6 5.0
4 8.0
3 10.0
dtype: float64
- Series去重操作
方法1 :drop_duplicates
def drop_duplicates(self, keep='first', inplace=False): pass
keep : {‘first’, ‘last’, False}, default ‘first’
‘first’ : Drop duplicates except for the first occurrence.
‘last’ : Drop duplicates except for the last occurrence.
False : Drop all duplicates.
inplace : boolean, default False
If True, performs operation inplace and returns None.
简单 解释 一下,
drop_duplicates 删除 重复的数据
keep 这个参数, 如果 有重复的数据 要保留哪一个 ,
- first 保留第一个出现的,
- last 保留最后一个出现的.
- False 代表不保留直接删除. (当然不是真的删除,只是返回了一个series,如果要直接删除需要和 inplace=True 结合使用)
inplace 参数 True, False 是否要原地删除数据.
- 看一个例子
s = pd.Series(['lama', 'cow', 'frank','lama', 'frank','beetle', 'lama', 'hippo'], name='animal')
s
0 lama
1 cow
2 frank
3 lama
4 frank
5 beetle
6 lama
7 hippo
Name: animal, dtype: object
#保留第一个
s.drop_duplicates(keep='first')
0 lama
1 cow
2 frank
5 beetle
7 hippo
Name: animal, dtype: object
# 保留最后一个
s.drop_duplicates(keep='last')
1 cow
4 frank
5 beetle
6 lama
7 hippo
Name: animal, dtype: object
# 直接删除 重复数据.
s.drop_duplicates(keep=False)
1 cow
5 beetle
7 hippo
Name: animal, dtype: object
# 当然 要想真的原地删除,需要 inplace=True 这个选项
s.drop_duplicates(keep=False,inplace=True)
s
1 cow
5 beetle
7 hippo
Name: animal, dtype: object
顺便提下 这个方法 s.duplicated(keep=False)
用来判断是否是重复数据,标记 为True or False
Series.duplicated(keep='first')[source]
Indicate duplicate Series values.
Duplicated values are indicated as True values in the resulting Series. Either all duplicates, all except the first or all except the last occurrence of duplicates can be indicated.
Parameters: keep : {‘first’, ‘last’, False}, default ‘first’
‘first’ : Mark duplicates as True except for the first occurrence.
‘last’ : Mark duplicates as True except for the last occurrence.
False : Mark all duplicates as True.
Returns: pandas.core.series.Series
keep 有三个值 first ,last ,False
如果 keep first 第一次出现是 False ,其他都是True
last 最后一次出现标记为 False ,其他情况标记为True
False 只要出现 就为 True
s2 = pd.Series(['lama', 'cow', 'frank','lama', 'frank','beetle', 'lama', 'hippo'], name='animal')
s2
0 lama
1 cow
2 frank
3 lama
4 frank
5 beetle
6 lama
7 hippo
Name: animal, dtype: object
s2.duplicated(keep='first')
0 False
1 False
2 False
3 True # 第二次出现
4 True # 第二次出现
5 False
6 True # 第三次出现
7 False
Name: animal, dtype: bool
s2.duplicated(keep='last')
0 True # lama 第一次出现
1 False
2 True
3 True # lama 第二次出现
4 False
5 False
6 False # lama 第三次出现 ,也是最后一次出现
7 False
Name: animal, dtype: bool
# 只要重复出现就为 True
s2.duplicated(keep=False)
0 True
1 False
2 True
3 True
4 True
5 False
6 True
7 False
Name: animal, dtype: bool
方法2:Series.unique 方法
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unique.html#pandas.Series.unique
Series.unique()[source]
Return unique values of Series object.
Uniques are returned in order of appearance. Hash table-based unique, therefore does NOT sort.
Returns: ndarray or CategoricalThe unique values returned as a NumPy array. In case of categorical data type, returned as a Categorical.
该方法 直接就返回 array 保留一个 返回一个 array 对象
这个方法几乎没有什么参数,直接返回一个去重的array 对象.
The unique values returned as a NumPy array.
s = pd.Series([2, 1, 3, 3,4,1,2], name='number')
s.unique()
array([2, 1, 3, 4])
s
0 2
1 1
2 3
3 3
4 4
5 1
6 2
Name: number, dtype: int64
3.常用的一些对series 的操作
import pandas as pd
import numpy as np
s = pd.Series(data= range(10),name='numbers',index=[ chr(i) for i in range(97,107)])
# 获取series的名称
s.name
'numbers'
# 获取所有的索引
print(s.index)
# 获取所有的值
print(s.values)
# 判断是否为nan
print(s.isnull())
print(pd.isnull(s))
# 根据index 访问值
# 打印所有的index
print(s.index)
print(s.get('b'))
print(s['b'])
# 一次访问多个不连续的值.
# 传入一个 list ,值是index [index,index,index,]
print(s[['a', 'b', 'f', 'j']])
# 获取series 的数据个数(Attributes)
print(s.size)
10
4 diff 函数
参考文档
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html#pandas.Series.diff
Calculates the difference of a Series element compared with another element in the Series (default is element in previous row).
Parameters: periods : int, default 1Periods to shift for calculating difference, accepts negative values.
Returns: diffed : Series
diff 默认是 后一个值 减去 前面一个值, 这样第一个就是 NaN , 后面都会有结果 .
有periods 可以设置 怎么减, 2 跨两个减, 0 自己减自己. (当前index 对应的值相减)
-1 前面减去后面一个值 . (就是index小的减去index 大的.
values 里面 后面减去前面的值,如果没有就是NaN , periods 默认是1 ,如果 是2 就是跨两个数相减.
s = pd.Series([1, 1, 2, 3, 5, 8])
s = pd.Series([1, 1, 2, 3, 5, 8])
s.diff()
0 NaN
1 0.0
2 1.0
3 1.0
4 2.0
5 3.0
dtype: float64
s.diff(3)
0 NaN
1 NaN
2 NaN
3 2.0 # 3-1
4 4.0 # 5-1
5 6.0 # 8-2
dtype: float64
s
0 1
1 1
2 2
3 3
4 5
5 8
dtype: int64
s.diff()
0 NaN
1 0.0
2 1.0
3 1.0
4 2.0
5 3.0
dtype: float64
s.diff(2)
0 NaN
1 NaN
2 1.0
3 2.0
4 3.0
5 5.0
dtype: float64
s
0 1
1 1
2 2
3 3
4 5
5 8
dtype: int64
s.diff(periods=2)
0 NaN
1 NaN
2 1.0
3 2.0
4 3.0
5 5.0
dtype: float64
s.diff(periods=-1)
0 0.0
1 -1.0
2 -1.0
3 -2.0
4 -3.0
5 NaN
dtype: float64
s.diff(periods=-2)
0 -1.0
1 -2.0
2 -3.0
3 -5.0
4 NaN
5 NaN
dtype: float64
# 自己减自己肯定是0
s.diff(0)
0 0.0
1 0.0
2 0.0
3 0.0
4 0.0
5 0.0
dtype: float64
- series 如何判断是否为空值
断是否是缺失 值
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isna.html#pandas.Series.isna
# 判断是否为None , 如果为 None,返回 True
series.isnull()
series.isna()
# 判断是否不为None , 如果不为None ,返回 True
series.notnull()
series.notna()
s= pd.Series([1, 8,10, np.NaN])
s
0 1.0
1 8.0
2 10.0
3 NaN
dtype: float64
# 是否为None
s.isna()
0 False
1 False
2 False
3 True
dtype: bool
s.isnull()
0 False
1 False
2 False
3 True
dtype: bool
# 是否不为None
s.notnull()
0 True
1 True
2 True
3 False
dtype: bool
s.notna()
0 True
1 True
2 True
3 False
dtype: bool
6 series.tolist() 方法, 返回一个list 根据values 的值,返回 一个list
Return a list of the values.
通过 series 转成 python 的list 对象
s= pd.Series([1, 8,10, np.NaN])
s.tolist()
[1.0, 8.0, 10.0, nan]
s
0 1.0
1 8.0
2 10.0
3 NaN
dtype: float64
s.tolist()
[1.0, 8.0, 10.0, nan]
s= pd.Series(['laoda','laoer','laosan'],name='person')
s
0 laoda
1 laoer
2 laosan
Name: person, dtype: object
s.tolist()
['laoda', 'laoer', 'laosan']
总结
本文总结了series常用的操作,Series 做为pandas 的核心对象之一,其实有很多方法 和dataframe 是差不多的。更多的了解还请查询 官方文档,里面有详细的介绍.
参考文档
Series index 官方首页 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html