Python3--我的代码库之Pandas库之Series(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c_air_c/article/details/81228297

1、什么是Series?

  • 简单地讲,就是一组带标签数组
  • 由一组数据和与之相关的标签组成的一维数组对象
标签
a 1
b 2
c 3
d 4

2、Series的特征

  • 数组中的数据类型可以为任意的数据类型;
  • 数组中的数据一般为同一种数据类型。

3、创建Series

3.1 导入Pandas
import pandas as pd
3.2 创建Series
s = pd.Series(data,index = index) #一般通用形式
3.3 通过列表list
s = pd.Series([10,20,30,40])
print(s)

0 10
1 20
2 30
3 40
dtype: int64

3.4 通过字典dict
dict_1 = pd.Series({'a':10,'b':40,'c':5})
print(dict_1)

a 10
b 40
c 5
dtype: int64

3.5 通过array
array_1 = pd.Series(np.arange(10,15),index = list('abcde'))
print(array_1)

a 10
b 11
c 12
d 13
e 14
dtype: int64

4、Series属性

4.1 获取index
array_1.index #即Series.index[0]

Index([‘a’, ‘b’, ‘c’, ‘d’, ‘e’], dtype=’object’)

4.2 通过赋值整体地修改索引值,索引值不能被单个修改
array_1.index = ['aa','bb','cc','dd','ff']
array_1.index

Index([‘aa’, ‘bb’, ‘cc’, ‘dd’, ‘ff’], dtype=’object’)

4.3 修改index名称
array_1.index.name = 'cou1'
print(array_1)

cou1
aa 10
bb 11
cc 12
dd 13
ff 14
Name: logs, dtype: int64

4.4 修改Series的名称,此处存疑,.name属性的作用?
   array_1.name = 'new_logs'
   print(array_1.name)

new_logs


此处说明,Series与其Index都有name属性!

4.5 获取所有value值,返回一个数组
array_1.values

array([10, 11, 12, 13, 14])

5、Series的索引

5.1 位置索引
print(array_1[0],array_1[-1],"\n",array_1[[0,1,3]])

10 14
cou1
aa 10
bb 11
dd 13
Name: new_logs, dtype: int64

5.2 名称索引
print(array_1[['aa','bb']])

cou1
aa 10
bb 11
Name: new_logs, dtype: int64

5.3 点索引
  • 只能取一个数
  • 过点来获取Series的对象,因此如果索引名不恰当(关键字)的话会与系统关键词重名,导致无法取数,故而在索引名与函数名重名时不推荐使用该方法
print(array_1.aa)

10


  • 1.一般情况下还是推荐用名称索引或者位置索引。
  • 2.如果确保不发生对象名字冲突的话,可以用点索引,这种写法会稍微快那么一点点,但我还是觉得何必那么麻烦记那么多方法。因此推荐名称索引和位置索引。

猜你喜欢

转载自blog.csdn.net/c_air_c/article/details/81228297