title: 学习 pandas [01]: 数据结构 slug: series-and-dataframe date: 2020-12-27 tags:
Pandas Jupyter python category: 数据分析 link: description: type: text 数据结构 pandas的数据类型主要有:
Series,类似一维数组 DataFrame,类似二维数组 Series 创建Series 1 pd.Series(data, index=index) data:可以是字典、一维数组、标量
index:索引列表,可以理解为行标签,根据Data的类型而不同。
通过字典创建Series 1 2 3 4 5 6 7 import numpy as np import pandas as pd # 通过字典创建,自动采用键值作为索引,若不指定index,则顺序同字典 d = {'b': 1, 'a': 0, 'c': 2} s = pd.Series(d) s b 1 a 0 c 2 dtype: int64 1 2 3 4 # 通过字典创建,自动采用键值作为索引,若指定index(包含键值),则顺序同index # index中若含有字典中不存在的键值,则Series中对应的值为NaN s = pd.Series(d, index=['a', 'b', 'c', 'd']) s a 0.0 b 1.0 c 2.0 d NaN dtype: float64 通过一维数组创建Series 1 2 3 4 5 l = np.random.randn(6) # 若不指定index,则自动生成数值型索引 s = pd.Series(l) s 0 0.215224 1 0.803700 2 1.141428 3 0.526450 4 0.577533 5 1.051918 dtype: float64 1 2 3 # 若指定index,则长度必须与数组相同 s = pd.Series(l, index=['a', 'b', 'c', 'd', 'e', 'f']) s a 0.215224 b 0.803700 c 1.141428 d 0.526450 e 0.577533 f 1.051918 dtype: float64 通过标量值创建Series 此方法创建出的Series,每行值都相同。
...