Pandas模块之Series:01-基本创建

基本概念

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

import numpy as np
import pandas as pd

s = pd.Series(np.random.randint(5,size = 5))
print(s)
print(type(s))
================================
0    1
1    1
2    4
3    1
4    4
dtype: int32
print(s.index,type(s.index))
print(s.values,type(s.values))
# .index查看series索引,类型为rangeindex
# .values查看series值,类型是ndarray
================================
<class 'pandas.core.series.Series'>
RangeIndex(start=0, stop=5, step=1) <class 'pandas.core.indexes.range.RangeIndex'>
[1 1 4 1 4] <class 'numpy.ndarray'>
  • series相比于ndarray,是一个自带索引index的数组 → 一维数组 + 对应索引。
    所以当只看series的值的时候,就是一个ndarray。
  • series和ndarray较相似,索引切片功能差别不大
  • series和dict相比,series更像一个有顺序的字典(dict本身不存在顺序),其索引原理与字典相似(一个用key,一个用index)
Series创建方法
方法1:由列表、字典创建

如果由列表来创建Series,其默认索引为0-n的数字。

s = pd.Series([1,2,3,4,5])
print(s)
================================
0    1
1    2
2    3
3    4
4    5
dtype: int64

由字典的key作为index,values作为values。

dic = {'a':1,'b':2,'c':3,'4':4, '5':5}
s = pd.Series(dic)
print(s)
================================
4    4
5    5
a    1
b    2
c    3
dtype: int64

在字典中,key的类型为字符串,如果values的类型不统一,那么在series中的数据类型会变为object,示例如下:

dic1 = {'a':'ssd','v':'ss','c':213}
s = pd.Series(dic1)
print(s)
================================
a    ssd
c    213
v     ss
dtype: object
方法2:由数组创建(一维数组)
arr = np.random.randint(10,size = 5)
s1 = pd.Series(arr)
print(s1)
s2 = pd.Series(arr,index = ['a','b','c','d','e'],dtype = np.object)
#可以在生成Series的时候指定索引和数据类型
================================
0    1
1    3
2    6
3    8
4    4
dtype: int32
a    1
b    3
c    6
d    8
e    4
dtype: object
方法3:由标量创建

如果data是标量值,则必须提供索引。该值会重复,来匹配索引的长度。

s = pd.Series(10, index = range(4))
print(s)
================================
0    10
1    10
2    10
3    10
dtype: int64
Series名称属性
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))
================================
0   -1.029313
1   -0.622097
2    0.014037
3   -0.889526
4   -2.669976
dtype: float64
-----
0    1.617239
1    0.009555
2   -1.403812
3   -1.294809
4    0.007626
Name: test, dtype: float64
None test <class 'str'>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值