Python数据分析实战【第三章】2.2- Pandas数据结构Series:基本概念及创建【python】

【课程2.2】 Pandas数据结构Series:基本概念及创建

"一维数组"Serise

# Series 数据结构
# Series 是带有标签的一维数组,可以保存任何数据类型(整数,字符串,浮点数,Python对象等),轴标签统称为索引

import numpy as np
import pandas as pd  
# 导入numpy、pandas模块

s = pd.Series(np.random.rand(5))
print(s)
print(type(s))
# 查看数据、数据类型

print(s.index,type(s.index))
print(s.values,type(s.values))
# .index查看series索引,类型为rangeindex
# .values查看series值,类型是ndarray

# 核心:series相比于ndarray,是一个自带索引index的数组 → 一维数组 + 对应索引
# 所以当只看series的值的时候,就是一个ndarray
# series和ndarray较相似,索引切片功能差别不大
# series和dict相比,series更像一个有顺序的字典(dict本身不存在顺序),其索引原理与字典相似(一个用key,一个用index)
-----------------------------------------------------------------------
0    0.229773
1    0.357622
2    0.546116
3    0.734517
4    0.686645
dtype: float64
<class 'pandas.core.series.Series'>
RangeIndex(start=0, stop=5, step=1) <class 'pandas.indexes.range.RangeIndex'>
[ 0.22977307  0.35762236  0.54611623  0.73451707  0.68664496] <class 'numpy.ndarray'>

2.Series 创建方法一:由字典创建,字典的key就是index,values就是values

dic = {'a':1 ,'b':2 , 'c':3, '4':4, '5':5}
s = pd.Series(dic)
print(s)
# 注意:key肯定是字符串,假如values类型不止一个会怎么样? → dic = {'a':1 ,'b':'hello' , 'c':3, '4':4, '5':5}
-----------------------------------------------------------------------
4    4
5    5
a    1
b    2
c    3
dtype: int64

3.Series 创建方法二:由数组创建(一维数组)

arr = np.random.randn(5)
s = pd.Series(arr)
print(arr)
print(s)
# 默认index是从0开始,步长为1的数字

s = pd.Series(arr, index = ['a','b','c','d','e'],dtype = np.object)
print(s)
# index参数:设置index,长度保持一致
# dtype参数:设置数值类型
-----------------------------------------------------------------------
[ 0.11206121  0.1324684   0.59930544  0.34707543 -0.15652941]
0    0.112061
1    0.132468
2    0.599305
3    0.347075
4   -0.156529
dtype: float64
a    0.112061
b    0.132468
c    0.599305
d    0.347075
e   -0.156529
dtype: object

4.Series 创建方法三:由标量创建

s = pd.Series(10, index = range(4))
print(s)
# 如果data是标量值,则必须提供索引。该值会重复,来匹配索引的长度
-----------------------------------------------------------------------
0    10
1    10
2    10
3    10
dtype: int64

5.Series 名称属性:name

s1 = pd.Series(np.random.randn(5))
print(s1)
print('-----')
s2 = pd.Series(np.random.randn(5),name = 'test')
print(s2)
print(s1.name, s2.name,type(s2.name))
# name为Series的一个参数,创建一个数组的 名称
# .name方法:输出数组的名称,输出格式为str,如果没用定义输出名称,输出为None

s3 = s2.rename('hehehe')
print(s3)
print(s3.name, s2.name)
# .rename()重命名一个数组的名称,并且新指向一个数组,原数组不变
-----------------------------------------------------------------------
0   -0.403084
1    1.369383
2    1.134319
3   -0.635050
4    1.680211
dtype: float64
-----
0   -0.120014
1    1.967648
2    1.142626
3    0.234079
4    0.761357
Name: test, dtype: float64
None test <class 'str'>
0   -0.120014
1    1.967648
2    1.142626
3    0.234079
4    0.761357
Name: hehehe, dtype: float64
hehehe test
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章