Pandas入門——Series基本操作


Series學習

使用Python的列表創建Series:

import numpy as np
import pandas as pd
# 使用list創建
s1 = pd.Series([1,2,3,4]) # 可以發現索引index默認從0開始進行自動索引
s1
0    1
1    2
2    3
3    4
dtype: int64

 

# 值屬性,可以方便查看Series的值
s1.values
array([1, 2, 3, 4], dtype=int64)

 

# 索引index屬性,返回的是索引從開始到結束和間隔的值
s1.index 
RangeIndex(start=0, stop=4, step=1)


# 使用numpy的數組進行創建
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
 

# 通過字典進行創建
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

 
s4.values
array([1, 2, 3, 4], dtype=int64)

s4.index
Index(['A', 'B', 'C', 'D'], dtype='object')

s4['A']  # 根據索引取值
1

s4[s4>1] # 根據值得范圍取值
B    2
C    3
D    4
dtype: int64

 
s4.to_dict() # 把Series轉換為字典輸出,也就是說可以通過字典創建Series,也可以通過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

 
index_1 = ['A','B','C','D','E'] # 可單獨把索引寫出,再賦值給Series,同時多增加一個索引
s6 = pd.Series(s5, index=index_1)
s6  # 多增加的索引的值為NAN
A    1.0
B    2.0
C    3.0
D    4.0
E    NaN
dtype: float64


pd.isnull(s6) # 根據pd.isnall()判斷Series的元素是否有空值,如果有返回Ture,反之False
A    False
B    False
C    False
D    False
E     True
dtype: bool

 
pd.notnull(s6) # 類似的操作 
A     True
B     True
C     True
D     True
E    False
dtype: bool

 
s6.name = 'demo' # 給Series賦予名字
s6
A    1.0
B    2.0
C    3.0
D    4.0
E    NaN
Name: demo, dtype: float64

 

s6.index.name = 'demo_index' # 給索引起個名字
s6
demo_index
A    1.0
B    2.0
C    3.0
D    4.0
E    NaN
Name: demo, dtype: float64

 
s6.index 
Index(['A', 'B', 'C', 'D', 'E'], dtype='object', name='demo_index')

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM