1.Series结构
Series结构,也称Series序列,是Pandas常用的数据结构之。它是一种类似于一维数组的结构,由一组数据值(value)和一组标签(index)组成,其中标签与数据值具有对应关系。
标签不必是唯一的,但必须是可哈希类型。该对象既支持基于整数的索引,也支持基于标签的索引,并提供了许多方法来执行涉及索引的操作。ndarray的统计方法已被覆盖,以自动排除缺失的数据(目前表示为NaN)。
Series 可以保存任何数据类型,比如整数、字符串、浮点数、Python对象等,它的标签默认为整数,从0开始依次递增。
Series的结构图,如下所示:
list、ndarray转换为Series格式
import pandas as pd
import numpy as np
a=[3,7,5,8,2]
# 将列表转换为Series格式
b=pd.Series(a)
print(b)
print('a的类型: ',repr(type(a)),'\nb的类型: ',repr(type(b)))
'''
0 3
1 7
2 5
3 8
4 2
dtype: int64
a的类型: <class 'list'>
b的类型: <class 'pandas.core.series.Series'>
'''
npa=np.arange(1,6)
# 将ndarray转换为Series格式
b=pd.Series(npa)
print(b)
print('npa的类型: ',repr(type(npa)),'\nb的类型: ',repr(type(b)))
#输出b的标签
print(b.index)
#以元组形式输出b的标签
print(list(b.index))
#输出b的值以及值的数据类型
print(b.values,type(b.values))
'''
0 1
1 2
2 3
3 4
4 5
dtype: int32
npa的类型: <class 'numpy.ndarray'>
b的类型: <class 'pandas.core.series.Series'>
RangeIndex(start=0, stop=5, step=1)
[0, 1, 2, 3, 4]
[1 2 3 4 5] <class 'numpy.ndarray'>
'''
# 添加一个元素进来
b[-1]='a'
print('查找标签为-1的元素值:',repr(b[-1]))
# 查询没有的标签,会报错:
print(b[-2])
'''
查找标签为-1的元素值: 'a'
'''
dic转换为Series
dic = {'a': 1, 'b': 2,'c': 3}
b=pd.Series(data=dic)
print(b)
# 如果标签不是整形数,也可以用标签的下标获取对应的值
print('标签取值: ',b['a'], '\n标签下标取值:',b[0])
'''
a 1
b 2
c 3
dtype: int64
标签取值: 1
标签下标取值: 1
'''
dic2 = {'a': 1, 0: 2,'c': 3}
b=pd.Series(data=dic2)
print(b)
# 如果标签里有整形数和其他类型的标签,就不能通过标签的下标来取值了,否则会报KeyError
print('标签取值: ',b[0], '\n标签下标取值:',b[1])
'''
a 1
0 2
c 3
dtype: int64
Traceback (most recent call last):
File "C:\Users\13529\PycharmProjects\test01\venv\lib\site-packages\pandas\core\indexes\base.py", line 3361, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 1
'''
# 当传递的索引值未匹配对应的字典键时,使用NaN(非数字)填充。
dic3 = {'a': 'str', 'b': 2,'c': 3}
b=pd.Series(data=dic3,index=['x','a','y','z'])
print(b)
'''
x NaN
a str
y NaN
z NaN
dtype: object
'''
dic4={'apple':1,'banana':1.2,'orange':1.3}
b=pd.Series(dic4)
b.name = "Fruit_Data"
b.index.name = "Fruit_Name"
print(b)
'''
Fruit_Name
apple 1.0
banana 1.2
orange 1.3
Name: Fruit_Data, dtype: float64
'''
将Series转换为DataFrame类型:
#使用Series创建DataFrame类型
df=pd.DataFrame(b)
print(df,'\n'+'df的数据类型: '+repr(type(df)))
print("**"*20)
#输出City_Data列的数据和类型
print(df['Fruit_Data'],'\n'+'df中的Fruit_Data数据类型: '+repr(type(df['Fruit_Data'])))
'''
Fruit_Data
Fruit_Name
apple 1.0
banana 1.2
orange 1.3
df的数据类型: <class 'pandas.core.frame.DataFrame'>
****************************************
Fruit_Name
apple 1.0
banana 1.2
orange 1.3
Name: Fruit_Data, dtype: float64
df中的Fruit_Data数据类型: <class 'pandas.core.series.Series'>
'''
标签索引的唯一并不是强制性的,尽管pandas函数(比如reindex)需要标签是唯一的。
# 当一个标签index对应多个值时,可以用loc[index]进行查找
a = pd.Series(range(5), index=["A", "A", "B", "C", "C"])
print('索引A对应的值:')
print(a.loc["A"])
# 判断该Series中的标签是否是唯一的
print(a.index.is_unique)
'''
索引A对应的值:
A 0
A 1
dtype: int64
标签是否是唯一: False
'''
2.Series基本方法
head()、tail()
s=pd.Series(np.random.rand(10))
# 默认取前5条数据
print(s.head())
# 取前1条数据
print(s.head(1))
# 默认取后5条数据
print(s.tail())
# 取后7条数据
print(s.tail(7))
'''
0 0.708893
1 0.631392
2 0.031043
3 0.625734
4 0.672718
dtype: float64
0 0.708893
dtype: float64
5 0.614755
6 0.839329
7 0.030989
8 0.636356
9 0.936704
dtype: float64
3 0.625734
4 0.672718
5 0.614755
6 0.839329
7 0.030989
8 0.636356
9 0.936704
dtype: float64
'''
reindex()重新索引
s=pd.Series(np.random.rand(5),index=list("abcde"))
print("s")
print(s)
# 新索引在上一个索引中不存在,生成新对象时,对应的值,设置为NaN
s1 = s.reindex(list("c7ed9"))
print("s1")
print(s1)
# 设置填充值,可将NaN填充
s2 = s.reindex(list("cde12"),fill_value=2)
print("s2")
print(s2)
'''
s
a 0.477522
b 0.626260
c 0.302472
d 0.684824
e 0.209174
dtype: float64
s1
c 0.302472
7 NaN
e 0.209174
d 0.684824
9 NaN
dtype: float64
s2
c 0.302472
d 0.684824
e 0.209174
1 2.000000
2 2.000000
dtype: float64
'''
对齐运算
几个不同的series可以按索引对齐进行运算,如果没对齐的位置则补NaN,最后也可以填充NaN
s1=pd.Series(np.random.rand(3),index=['c','b','a'])
s2=pd.Series(np.random.rand(3),index=['a','b','d'])
print("s1")
print(s1)
print("s2")
print(s2)
print("s1+s2")
print(s1+s2)
'''
s1
c 0.001765
b 0.433448
a 0.192272
dtype: float64
s2
a 0.176781
b 0.778649
d 0.554887
dtype: float64
s1+s2
a 0.369054
b 1.212097
c NaN
d NaN
dtype: float64
'''
drop(),删除索引值为的元素,但当删除不存在的键时,会报错
s1=pd.Series(np.random.rand(3),index=['c','b','a'])
s1=s1.drop('c')
print(s1)
'''
b 0.827299
a 0.858903
dtype: float64
'''
# 删除不存在的键时,会报错
s1=s1.drop('d')
'''
KeyError: "['d'] not found in axis"
'''