三种创建Series的方法
1.python list
#series 和numpy中的array有一点相似
#创建series
s1 = pd.Series([1, 2, 3, 4])
s1 #包含数据,以及label/index
>>>
0 1
1 2
2 3
3 4
dtype: int64
s1.values #查看数据
>>>array([1, 2, 3, 4], dtype=int64)
s1.index #查看index
>>>RangeIndex(start=0, stop=4, step=1)
2.通过numpy的arange创建series
s2 = pd.Series(np.arange(10))
s2
>>>
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
dtype: int32
3.通过python字典
s3 = pd.Series({'1':1, "2":2, "3":3})
s3
>>>
1 1
2 2
3 3
dtype: int64
s3.values
>>>array([1, 2, 3], dtype=int64)
s3.index #注意与前两种的不同
>>>Index(['1', '2', '3'], dtype='object')
注意,以下方式等同
s4 = pd.Series([1, 2, 3, 4], index=['A', 'B','C', 'D'])
s4
>>>
A 1
B 2
C 3
D 4
dtype: int64
pandas的Series和python字典联系紧密
s4 ['A']
>>>1
s4[s4>2]
>>>
C 3
D 4
dtype: int64
Series和python字典可以互换
s4.to_dict() #to_dict作用将Series转化为字典
>>>{'A': 1, 'B': 2, 'C': 3, 'D': 4}
s5 = pd.Series(s4.to_dict())
s5
>>>
A 1
B 2
C 3
D 4
dtype: int64