Pandas的筆記-pandas.Series
pandas.series(data=None,index=None)
一.建立list
使用pandas建立一個list當練習
#pandas筆記1
import pandas as pd
abc= pd.Series([11,22,33,44,55])
print(abc)
輸出結果:
0 11
1 22
2 33
3 44
4 55
dtype: int64
他會將串列自動從0開始編排,所以我輸入abc[0]結果會跳出11,以此類推。
二.建立dict
使用pandas建立一個dict當練習
#pandas筆記2
import pandas as pd
abc= pd.Series({'台灣':'Taiwan','日本':'Japan','香港':'Hongkong'})
print(abc)
輸出結果:
台灣 Taiwan
日本 Japan
香港 Hongkong
dtype: object
三.將字典的鍵與值分開來寫串列,做成dict
#pandas筆記3
import pandas as pd
abc_key=['台灣','日本','香港']
abc_value=['Taiwan','Japan','HongKong']
abc= pd.Series(abc_value,index=abc_key)
print(abc)
同上二.建立dict結果。
~請支持《落葉筆記》原創文章。原文標題:
Pandas的筆記-pandas.Series
四.數字的運算
(1.)兩個不同的Series做運算
兩個不同的Series也可以做值的簡單運算,我先說明錯誤範例
#pandas筆記4,錯誤範例
import pandas as pd
Monday_cost=pd.Series({'電費':'150','水費':'100','生活費':'2000'})
Tuesday_cost=pd.Series({'電費':'200','水費':'150','生活費':'2500','網路費':'800'})
total_list=Monday_cost + Tuesday_cost
print(total_list)
輸出結果:
水費 100150
生活費 20002500
網路費 NaN
電費 150200
dtype: object
看起來是文字’100’放在’150’前面了,沒有當作真正的數字在計算,這是因為我在各個花費中把數字加上’ ‘了,type(Monday_cost[0])結果是str。
只需把’ ‘刪除即可。
#pandas筆記4
import pandas as pd
Monday_cost=pd.Series({'電費':150,'水費':100,'生活費':2000})
Tuesday_cost=pd.Series({'電費':200,'水費':150,'生活費':2500,'網路費':800})
total_list=Monday_cost + Tuesday_cost
print(total_list)
輸出結果:
水費 250.0
生活費 4500.0
網路費 NaN
電費 350.0
dtype: float64
這時出現了NaN,意思是Not a Number,因為兩個Series相加時,不同的索引的索引內容無法正確做運算。這時有個解決方法。
#pandas筆記5
import pandas as pd
Monday_cost=pd.Series({'電費':150,'水費':100,'生活費':2000})
Tuesday_cost=pd.Series({'電費':200,'水費':150,'生活費':2500,'網路費':800})
total_list=Monday_cost.add(Tuesday_cost,fill_value=0)
print(total_list)
輸出結果:
水費 250.0
生活費 4500.0
網路費 800.0
電費 350.0
dtype: float64
(2.)簡單的數學運算
兩個Series的加減乘除
#pandas筆記6
import pandas as pd
aa=pd.Series({'a':1,'b':3,'c':7})
bb=pd.Series({'a':2,'b':5,'c':9})
print(aa+bb)
print(aa-bb)
print(aa*bb)
print(aa/bb)
輸出結果:
a 3
b 8
c 16
dtype: int64
a -1
b -2
c -2
dtype: int64
a 2
b 15
c 63
dtype: int64
a 0.500000
b 0.600000
c 0.777778
dtype: float64
(3.)選取某個鍵來做計算
我只想知道某個鍵他們的值相加是多少時,可以這樣輸入
#DATA
import pandas as pd
Monday_cost=pd.Series({'電費':150,'水費':100,'生活費':2000})
Tuesday_cost=pd.Series({'電費':200,'水費':150,'生活費':2500,'網路費':800})
total_list=Monday_cost.add(Tuesday_cost,fill_value=0)
Monday_cost[‘水費’]+Tuesday_cost[‘水費’]
輸出結果: 250
接著在total_list另外增加一個字典是總和:
#pandas筆記7
import pandas as pd
Monday_cost=pd.Series({'電費':150,'水費':100,'生活費':2000})
Tuesday_cost=pd.Series({'電費':200,'水費':150,'生活費':2500,'網路費':800})
total_list=Monday_cost.add(Tuesday_cost,fill_value=0)
total=total_list[0]+total_list[1]+total_list[2]+total_list[3]
total_list['總和']=total
print(total_list)
輸出結果:
水費 250.0
生活費 4500.0
網路費 800.0
電費 350.0
總和 5900.0
dtype: float64
是否一目了然一月和二月的總花費了呢?
發佈留言