数据结构4 :Series(Pandas库)

Pandas 的数据结构主要是:Series(一维数组),DataFrame(二维数组)。Series是由索引和内容组成,索引在左边,内容在右边,如 ‘索引’:内容 这样的形式。索引是Pandas库的数据结构中的一大特性,它主要的功能是帮助我们更快速地定位数据。

1 Pandas中创建Series

1.1 pd.Series(dict数据)

import pandas as pd
a=pd.Series({"class": "3",
             "name": "fry",
             "grade": 1})
print(a)
# class      3
# name     fry
# grade      1
# dtype: object

1.2 pd.Series(ndarray数据)

x = np.array([1, 2, 3])
print(pd.Series(x))
# 0    1
# 1    2
# 2    3
# dtype: int32

2 指定Series索引

Series的索引如果没有提前指定默认从0开始。可以通过以下方式来指定index:

2.1 创建series后再添加index

import pandas as pd
import numpy as np
x = np.array([1, 2, 3])
y=pd.Series(x)
y.index=['a','b','c']
print(y)
# a    1
# b    2
# c    3
# dtype: int32

2.2 创建series的同时添加index属性

import pandas as pd
import numpy as np
x = np.array([1, 2, 3])
y=pd.Series(x,index=['a','b','c'])
print(y)
# a    1
# b    2
# c    3
# dtype: int32

 3 Series读取数据

通过方括号+索引/下标值的方式读取对应索引的数据

import pandas as pd
import numpy as np
x = np.array([1, 2, 3])
y=pd.Series(x)
y.index=['a','b','c']
print(y['a']) #[索引]
print(y[2]) #[下标]
#Out1: 1
#Out2: 3

 需要说明的是,虽然Series的索引是可以重新定义的,但是下标始终是不变的(0开始)。

3 Series的切片

通过方括号+下标值/索引值+冒号的形式来截取数据。

import pandas as pd
import numpy as np
x = np.array([1, 2, 3])
y=pd.Series(x)
y.index=['a','b','c']
print(y['a':'c']) #闭区间
print(y[1:2]) #左到右不到
# a    1
# b    2
# c    3
# dtype: int32
# b    2
#dtype: int32

需要说明的是,用下标(原始索引)来切片时是左到右不到的。但是Series的索引是可以重新定义的,用重新定义后的索引来切片时是左到右不到的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值