pandas数组(pandas Series)-(2)

 pandas Series 比 numpy array 要强大很多,体现在很多方面

首先, pandas Series 有一些方法,比如:

 describe 方法可以给出 Series 的一些分析数据:

import pandas as pd

s =  pd.Series([1,2,3,4])
d = s.describe()
print(d)
count    4.000000
mean     2.500000
std      1.290994
min      1.000000
25%      1.750000
50%      2.500000
75%      3.250000
max      4.000000
dtype: float64

其次, pandas Series 和 numpy array  最大的区别是,  pandas Series有'索引'这一概念:

创建 pandas Series的时候,可以包含一个作为索引值的数组:

life = pd.Series([74.7, 75., 80., 72.8], index=['city1', 'city2', 'city3', 'city4'])
print(life)

其中 ['city1', 'city2', 'city3', 'city4']数组就是索引数组,会被作为 life   Series 的索引值:

city1    74.7
city2    75.0
city3    80.0
city4    72.8
dtype: float64

 pandas Series 像是 list 与 dict 的结合, list 是有序的,按照位置0,1,2,3...来获取对应位置的元素, dict 是无序的,通过 key 来获取对应的元素, pandas Series 既有序,又有索引 key , 可以通过 key 来获取元素:

print(life['city1'])

# 结果 74.7

也可以通过位置索引来获取元素:

print(life[0])

# 结果 74.7

为了更好的区分位置索引和 key 索引, pandas Series 提供了两个方法:

print(life.loc['city1'])
print(life.iloc[0])

 loc 传入 key 索引值, iloc 传入位置索引值.

猜你喜欢

转载自www.cnblogs.com/liulangmao/p/9206810.html