数据分析之Series对象的创建
pandas
中的核心对象是Series
和DataFrame
In[2]:
|
|
Series
Series
是pandas
中暴露给我们使用的基本对象,它是由相同元素类型构成的一维数据结构,同时具有列表和字典的属性(字典的属性由索引赋予)。
- Series:有序,有索引
- list: 有序,无索引
- dict: 无序,有索引
预览
In [3]:
|
|
Out[3]:
|
|
In [4]:
s.index # 四个属性之一:索引
Out[4]:
Index(['a', 'b', 'c'], dtype='object')
In [5]:
s.name # 四个属性之二:名字,
Out[5]:
'sss'
In [6]:
s.values # 四个属性之三:值
Out[6]:
array([1, 2, 3], dtype=int64)
In [7]:
s.dtype # 四个属性之四:元素类型
Out[7]:
dtype('int64')
创建
pd.Series(data=None, index=None, name = None)
- data:多种类型,见下面具体介绍
- index:索引
- name:对data的说明,用的不多,一般在和DataFrame、Index互相转换时才需要。
data无索引
- 如果
data
为ndarray(1D)
或list(1D)
,那么其缺少Series
需要的索引信息; - 如果提供
index
,则必须和data
长度相同; - 如果不提供
index
,那么其将生成默认数值索引range(0, data.shape[0])
。
In [8]:
|
|
Out[8]:
|
|
data有索引
- 如果
data
为Series
或dict
,那么其已经提供了Series
需要的索引信息,所以index
项是不需要提供的; - 如果额外提供了
index
项,那么其将对当前构建的Series
进行 重索引(增删)(等同于reindex
操作)。
In [9]:
|
|
Out[9]:
|
|
如上,
index
项用于从当前已有索引中匹配出相同的行,如果当前索引缺失给定的索引,则填充NaN(NaN:not a number为pandas缺失值标记)