Series是一种类似一维数据的数据结构,由数据(values)及索引(indexs)组成。
Series 由索引(index)和列组成,函数如下:
pandas.Series( data, index, dtype, name, copy)
1.Series入门实例:
import pandas as pd
a = [1, 2, 3]
lans = ["Java", "C++", "Python"]
citys = {"010": "北京", "020": "广州", "029": "西安","028":"成都"}
s1 = pd.Series(a)
s2 = pd.Series(lans, index = ["first", "second", "third"])
s3 = pd.Series(citys);
# 设置 Series 名称
s4 = pd.Series(citys, index = ["029", "028"], name="west-ctiys" )
print(s1)
print(s2)
print(s3)
print(s4)
print(s1[1])
print(s2["second"])
print(s3["029"])
#Series的切片操作
print(s3[1:3])
#数据修改
s2["first"]="Javascript"
print(s2)
#Pandas会根据索引index索引对相应数据进行计算。如代码所示,可以直接对Series结构进行加减乘除运算符,当出现index不匹配的情况时会输出NaN。
sr1 = pd.Series([1, 2, 3, 4],['a','b','c','d'])
sr2 = pd.Series([1, 5, 8, 9],['a','c','e','f'])
print(sr2 - sr1)
运行效果:
0 1
1 2
2 3
dtype: int64
first Java
second C++
third Python
dtype: object
010 北京
020 广州
029 西安
028 成都
dtype: object
029 西安
028 成都
Name: west-ctiys, dtype: object
2
C++
西安
020 广州
029 西安
dtype: object
first Javascript
second C++
third Python
dtype: object
a 0.0
b NaN
c 2.0
d NaN
e NaN
f NaN
dtype: float64
2.Series缺失数据处理
| 方法 | 说明 |
|---|---|
| dropna() | 过滤掉值为NaN的行 |
| fillna() | 填充缺失数据 |
| isnull() | 检测缺失值,缺失值为True,非缺失值为False |
| notnull() | 检测非缺失值,和 isnull() 方法相反,非缺失值为True,缺失值为False |
实例:
import numpy as np
import pandas as pd
df = pd.Series([1, 2, 3, 4, np.nan], index=['a', 'b', 'c', 'd', 'e'])
print(df)
print(df.dropna())
print(df.fillna(0))
print(df.isnull())
print(df.notnull())
运行效果:
a 1.0
b 2.0
c 3.0
d 4.0
e NaN
dtype: float64
a 1.0
b 2.0
c 3.0
d 4.0
dtype: float64
a 1.0
b 2.0
c 3.0
d 4.0
e 0.0
dtype: float64
a False
b False
c False
d False
e True
dtype: bool
a True
b True
c True
d True
e False
dtype: bool