Pandas之Series


# Series 數據結構
# Series 是帶有標簽的一維數組,可以保存任何數據類型(整數,字符串,浮點數,Python對象等),軸標簽統稱為索引

import numpy as np
import pandas as pd  
# 導入numpy、pandas模塊

s = pd.Series(np.random.rand(5))
print(s)
print(type(s))
# 查看數據、數據類型

print(s.index,type(s.index))
print(s.values,type(s.values))
# .index查看series索引,類型為rangeindex
# .values查看series值,類型是ndarray

# 核心:series相比於ndarray,是一個自帶索引index的數組 → 一維數組 + 對應索引
# 所以當只看series的值的時候,就是一個ndarray
# series和ndarray較相似,索引切片功能差別不大
# series和dict相比,series更像一個有順序的字典(dict本身不存在順序),其索引原理與字典相似(一個用key,一個用index)

  輸出:

0    0.229773
1    0.357622
2    0.546116
3    0.734517
4    0.686645
dtype: float64
<class 'pandas.core.series.Series'>
RangeIndex(start=0, stop=5, step=1) <class 'pandas.indexes.range.RangeIndex'>
[ 0.22977307  0.35762236  0.54611623  0.73451707  0.68664496] <class 'numpy.ndarray'>

 

# Series 創建方法一:由字典創建,字典的key就是index,values就是values

dic = {'a':1 ,'b':2 , 'c':3, '4':4, '5':5}
s = pd.Series(dic)
print(s)
# 注意:key肯定是字符串,假如values類型不止一個會怎么樣? → dic = {'a':1 ,'b':'hello' , 'c':3, '4':4, '5':5}

  輸出:

4    4
5    5
a    1
b    2
c    3
dtype: int64

 

# Series 創建方法二:由數組創建(一維數組)

arr = np.random.randn(5)
s = pd.Series(arr)
print(arr)
print(s)
# 默認index是從0開始,步長為1的數字

s = pd.Series(arr, index = ['a','b','c','d','e'],dtype = np.object)
print(s)
# index參數:設置index,長度保持一致
# dtype參數:設置數值類型

  輸出:

[ 0.11206121  0.1324684   0.59930544  0.34707543 -0.15652941]
0    0.112061
1    0.132468
2    0.599305
3    0.347075
4   -0.156529
dtype: float64
a    0.112061
b    0.132468
c    0.599305
d    0.347075
e   -0.156529
dtype: object

 

# Series 創建方法三:由標量創建

s = pd.Series(10, index = range(4))
print(s)
# 如果data是標量值,則必須提供索引。該值會重復,來匹配索引的長度

  輸出:

0    10
1    10
2    10
3    10
dtype: int64

 

  

# Series 名稱屬性:name

s1 = pd.Series(np.random.randn(5))
print(s1)
print('-----')
s2 = pd.Series(np.random.randn(5),name = 'test')
print(s2)
print(s1.name, s2.name,type(s2.name))
# name為Series的一個參數,創建一個數組的 名稱
# .name方法:輸出數組的名稱,輸出格式為str,如果沒用定義輸出名稱,輸出為None

s3 = s2.rename('hehehe')
print(s3)
print(s3.name, s2.name)
# .rename()重命名一個數組的名稱,並且新指向一個數組,原數組不變

  輸出:

0   -0.403084
1    1.369383
2    1.134319
3   -0.635050
4    1.680211
dtype: float64
-----
0   -0.120014
1    1.967648
2    1.142626
3    0.234079
4    0.761357
Name: test, dtype: float64
None test <class 'str'>
0   -0.120014
1    1.967648
2    1.142626
3    0.234079
4    0.761357
Name: hehehe, dtype: float64
hehehe test

 

# 位置下標,類似序列

s = pd.Series(np.random.rand(5))
print(s)
print(s[0],type(s[0]),s[0].dtype)
print(float(s[0]),type(float(s[0])))
#print(s[-1])
# 位置下標從0開始
# 輸出結果為numpy.float格式,
# 可以通過float()函數轉換為python float格式
# numpy.float與float占用字節不同
# s[-1]結果如何?

  輸出:

0    0.924575
1    0.988654
2    0.426333
3    0.216504
4    0.453570
dtype: float64
0.924575004833 <class 'numpy.float64'> float64
0.9245750048328816 <class 'float'>

 

  

# 標簽索引

s = pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
print(s)
print(s['a'],type(s['a']),s['a'].dtype)
# 方法類似下標索引,用[]表示,內寫上index,注意index是字符串

sci = s[['a','b','e']]
print(sci,type(sci))
# 如果需要選擇多個標簽的值,用[[]]來表示(相當於[]中包含一個列表)
# 多標簽索引結果是新的數組

  輸出:

a    0.714630
b    0.213957
c    0.172188
d    0.972158
e    0.875175
dtype: float64
0.714630383451 <class 'numpy.float64'> float64
a    0.714630
b    0.213957
e    0.875175
dtype: float64 <class 'pandas.core.series.Series'>

 

  

# 切片索引

s1 = pd.Series(np.random.rand(5))
s2 = pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
print(s1[1:4],s1[4])
print(s2['a':'c'],s2['c'])
print(s2[0:3],s2[3])
print('-----')
# 注意:用index做切片是末端包含

print(s2[:-1])
print(s2[::2])
# 下標索引做切片,和list寫法一樣

  輸出:

1    0.865967
2    0.114500
3    0.369301
dtype: float64 0.411702342342
a    0.717378
b    0.642561
c    0.391091
dtype: float64 0.39109096261
a    0.717378
b    0.642561
c    0.391091
dtype: float64 0.998978363818
-----
a    0.717378
b    0.642561
c    0.391091
d    0.998978
dtype: float64
a    0.717378
c    0.391091
e    0.957639
dtype: float64

 

  

# 布爾型索引

s = pd.Series(np.random.rand(3)*100)
s[4] = None  # 添加一個空值
print(s)
bs1 = s > 50
bs2 = s.isnull()
bs3 = s.notnull()
print(bs1, type(bs1), bs1.dtype)
print(bs2, type(bs2), bs2.dtype)
print(bs3, type(bs3), bs3.dtype)
print('-----')
# 數組做判斷之后,返回的是一個由布爾值組成的新的數組
# .isnull() / .notnull() 判斷是否為空值 (None代表空值,NaN代表有問題的數值,兩個都會識別為空值)

print(s[s > 50])
print(s[bs3])
# 布爾型索引方法:用[判斷條件]表示,其中判斷條件可以是 一個語句,或者是 一個布爾型數組!

  輸出:

0    2.03802
1    40.3989
2    25.2001
4       None
dtype: object
0    False
1    False
2    False
4    False
dtype: bool <class 'pandas.core.series.Series'> bool
0    False
1    False
2    False
4     True
dtype: bool <class 'pandas.core.series.Series'> bool
0     True
1     True
2     True
4    False
dtype: bool <class 'pandas.core.series.Series'> bool
-----
Series([], dtype: object)
0    2.03802
1    40.3989
2    25.2001
dtype: object

 

'''
【課程2.4】  Pandas數據結構Series:基本技巧

數據查看 / 重新索引 / 對齊 / 添加、修改、刪除值

'''
# 數據查看

s = pd.Series(np.random.rand(50))
print(s.head(10))
print(s.tail())
# .head()查看頭部數據
# .tail()查看尾部數據
# 默認查看5條

  輸出:

0    0.730540
1    0.116711
2    0.787693
3    0.969764
4    0.324540
5    0.061827
6    0.377060
7    0.820383
8    0.964477
9    0.451936
dtype: float64
45    0.899540
46    0.237008
47    0.298762
48    0.848487
49    0.829858
dtype: float64

 

# 重新索引reindex
# .reindex將會根據索引重新排序,如果當前索引不存在,則引入缺失值

s = pd.Series(np.random.rand(3), index = ['a','b','c'])
print(s)
s1 = s.reindex(['c','b','a','d'])
print(s1)
# .reindex()中也是寫列表
# 這里'd'索引不存在,所以值為NaN

s2 = s.reindex(['c','b','a','d'], fill_value = 0)
print(s2)
# fill_value參數:填充缺失值的值

  輸出:

a    0.343718
b    0.322228
c    0.746720
dtype: float64
c    0.746720
b    0.322228
a    0.343718
d         NaN
dtype: float64
c    0.746720
b    0.322228
a    0.343718
d    0.000000
dtype: float64

 

# Series對齊

s1 = pd.Series(np.random.rand(3), index = ['Jack','Marry','Tom'])
s2 = pd.Series(np.random.rand(3), index = ['Wang','Jack','Marry'])
print(s1)
print(s2)
print(s1+s2)
# Series 和 ndarray 之間的主要區別是,Series 上的操作會根據標簽自動對齊
# index順序不會影響數值計算,以標簽來計算
# 空值和任何值計算結果扔為空值

  輸出:

Jack     0.753732
Marry    0.180223
Tom      0.283704
dtype: float64
Wang     0.309128
Jack     0.533997
Marry    0.626126
dtype: float64
Jack     1.287729
Marry    0.806349
Tom           NaN
Wang          NaN
dtype: float64

 

# 刪除:.drop

s = pd.Series(np.random.rand(5), index = list('ngjur'))
print(s)
s1 = s.drop('n')
s2 = s.drop(['g','j'])
print(s1)
print(s2)
print(s)
# drop 刪除元素之后返回副本(inplace=False)

  輸出:

n    0.876587
g    0.594053
j    0.628232
u    0.360634
r    0.454483
dtype: float64
g    0.594053
j    0.628232
u    0.360634
r    0.454483
dtype: float64
n    0.876587
u    0.360634
r    0.454483
dtype: float64
n    0.876587
g    0.594053
j    0.628232
u    0.360634
r    0.454483
dtype: float64

 

  

# 添加

s1 = pd.Series(np.random.rand(5))
s2 = pd.Series(np.random.rand(5), index = list('ngjur'))
print(s1)
print(s2)
s1[5] = 100
s2['a'] = 100
print(s1)
print(s2)
print('-----')
# 直接通過下標索引/標簽index添加值

s3 = s1.append(s2)
print(s3)
print(s1)
# 通過.append方法,直接添加一個數組
# .append方法生成一個新的數組,不改變之前的數組

  輸出:

0    0.516447
1    0.699382
2    0.469513
3    0.589821
4    0.402188
dtype: float64
n    0.615641
g    0.451192
j    0.022328
u    0.977568
r    0.902041
dtype: float64
0      0.516447
1      0.699382
2      0.469513
3      0.589821
4      0.402188
5    100.000000
dtype: float64
n      0.615641
g      0.451192
j      0.022328
u      0.977568
r      0.902041
a    100.000000
dtype: float64
-----
0      0.516447
1      0.699382
2      0.469513
3      0.589821
4      0.402188
5    100.000000
n      0.615641
g      0.451192
j      0.022328
u      0.977568
r      0.902041
a    100.000000
dtype: float64
0      0.516447
1      0.699382
2      0.469513
3      0.589821
4      0.402188
5    100.000000
dtype: float64

 

# 修改

s = pd.Series(np.random.rand(3), index = ['a','b','c'])
print(s)
s['a'] = 100
s[['b','c']] = 200
print(s)
# 通過索引直接修改,類似序列

  輸出:

a    0.873604
b    0.244707
c    0.888685
dtype: float64
a    100.0
b    200.0
c    200.0
dtype: float64

 


免責聲明!

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



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