首页 > 编程笔记

Pandas Series对象常见属性

查看 Series 的相关属性,可以查看或更改该序列元素的类型以及索引。
In [1]: import pandas as pd
In [2]: a=pd.Series([0,1,2,3,4,5])

1)index属性

index 属性可以查看 Series 对象的索引,同样也可以直接赋值更改。我们使用 .loc 和 .iloc 对索引修改,前后做同样的处理,请体会 loc 和i loc 的区别,代码如下。
In [3]: a.index
Out[3]: RangeIndex(start=0, stop=6, step=1)
In [4]: a.loc[1]
Out[4]: 1
In [5]: a.iloc[1]
Out[5]: 1
改变了a的索引,这时 loc[1] 取倒数第2个位置的值,而 iloc[1] 仍然是取绝对位置为 1 的值。
In [6]: a.index = [5,4,3,2,1,0]
In [7]: a.index
Out[7]: Int64Index([5, 4, 3, 2, 1, 0], dtype='int64')
In [8]: a.loc[1]
Out[8]: 4
In [9]: a.iloc[1]
Out[9]: 1

2) size属性

size 属性可以用来查看 Series 的元素个数。
In [10]: a.size  # 查看数据的个数
Out[10]: 6

3) values属性

values 属性可以作为 Pandas 和 Numpy 中间转换的桥梁,通过 values 属性可以将 Pandas 中的数据格式转换为 Numpy 中数组的形式。
In [11]: a.values  # 查看返回值,返回的是一个Numpy中的array类型
Out[11]: array([0, 1, 2, 3, 4, 5], dtype=int64)

4) dtype属性

dtype 属性用来查看数据的类型,然后可以通过 astype 方法对数据类型进行更改。Pandas 支持很多数据类型,我们需要根据不同的使用场景选择不同的数据类型。
In [12]: a.dtype  # 查看数据类型
Out[12]: dtype('int64')
In [13]: a=a.astype('float64')
In [14]: a.dtype  # 查看数据类型 

优秀文章