本文参考官方文档地址
pandas有两种主要的操作对象Series(一维)和DataFrame(二维)。
1.Series
Series相当于pandas的一维数据结构,Series是一维的,能存储任意类型的数据(integers, strings, floating point numbers, Python objects, etc.),有一组索引与元素对应。其中的轴标签统称为索引。
1.1.创建Series
pd.Series(data, index=index)
- data:可以是下面三种类型
- python 字典、列表、元组
- ndarray
- a scalar value (like 5)
- index:表示轴标签列表,如果不指定,默认将是[0,..., len(data) - 1]作为默认index
1.2.使用
python列表创建Series
import pandas as pd
s = pd.Series([1,2,3,4,5])
s
输出:
0 1
1 2
2 3
3 4
4 5
dtype: int64
指定索引,需要注意index的长度必须和data长度一致,否则会报错,在测试版本中支持多个index名称相同
s = pd.Series([1,2,3,4,5], index=["a","b", "c", "d", "e"])
s
输出:
a 1
b 2
c 3
d 4
e 5
字典创建,字典key是无顺序的,所以创建出来的不一定会按照字典中的顺序,在python3.6之前或pandas版本是0.23之前,无法通过指定index来使得key有序,之后版本支持。
s = pd.Series({"name":"test", "age": 18})
s
输出:
age 18
name test
dtype: object
s = pd.Series({"name":"test", "age": 18},index=["name", "age", "class"])
s
输出:
name test
age 18
class NaN
dtype: object
网友评论