最近在做数据分析,所以用了一些pandas,但是在用的过程中,深感基础不扎实,不能达到灵活运用的程度,于是想着深入学一下pandas. 那么就先从series开始。
Series是pandas里最基础的一个数据结构,虽然DateFrame常常用得更多,但series仍然是pandas里基础的基础,DateFrame中的列也都是一个series.
series是一种一维的数组型对象,有点类似于python原生的列表,但考虑到他也有索引,所以跟字典也有一些类似 。

In [2]: import pandas as pd

In [3]: obj=pd.Series([4,7,-5,3])

In [4]: obj
Out[4]:
0    4
1    7
2   -5
3    3
dtype: int64

从上面的代码可以看到series是有索引的,这一点跟列表,数组有一定的区别,如果创建series时没有指定索引,那么会自动生成从0到n-1的索引。

In [6]: obj.values
Out[6]: array([ 4,  7, -5,  3], dtype=int64)

In [7]: obj.index
Out[7]: RangeIndex(start=0, stop=4, step=1)

可以通过values和index属性来访问series的值和属性,这里要注意,这两者都不是简单的列表类型,而是一些特殊的对象 。

In [8]: obj2 = pd.Series([4,7,-5,3],index=['d','b','a','c'])

In [9]: obj2
Out[9]:
d    4
b    7
a   -5
c    3
dtype: int64

In [10]: obj2.index
Out[10]: Index(['d', 'b', 'a', 'c'], dtype='object')

创建series时,也可以指定索引。

In [11]: obj2[1]
Out[11]: 7

In [12]: obj2.a
Out[12]: -5

In [13]: obj2['a']
Out[13]: -5

In [14]: obj2[1:2]
Out[14]:
b    7
dtype: int64

In [15]: obj2[1:3]
Out[15]:
b    7
a   -5
dtype: int64

In [16]: obj2[['c','a','d']]
Out[16]:
c    3
a   -5
d    4
dtype: int64

访问series元素的几种方法。他既能像列表一样直接用下标访问,也能像字典一样用索引访问,还能给定一个索引列表,访问一组索引的值。总体上还是比列表和字典都灵活。

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐