這裏來介紹一下pandas。由於知識點比較多,決定分幾篇介紹。
import numpy as np
import pandas as pd
#pandas是基於numpy的一個開源python庫。
#我認爲相當於python版excel
#series是一種一維數組,是基於ndarray設計的,但是他多了一個功能就是自定義標籤。
#說的明白點就是索引。因此可以通過這個索引來訪問數組中的數據
#創建語法如下:
#my_series=pd.Series(data,index)
countries=['USA','France','China','England']
my_data=[100,200,300,400]
my_series=pd.Series(my_data,countries)
my_series
USA 100
France 200
China 300
England 400
dtype: int64
#注意,index是可以省略的,這時系統會自動已默認index進行索引,這時的series就類似數組了。
pd.Series(my_data)
0 100
1 200
2 300
3 400
dtype: int64
#從numpy數組對象來創建Series:
np_arr=np.array(my_data)
pd.Series(np_arr)
0 100
1 200
2 300
3 400
dtype: int64
#從字典來創建Series似乎更方便
#pandas會自動把字典的鍵值設置成Series的index,並將對應的values放在和索引對應的data裏
#這也證明了,pandas的Series可以存放各種不同類型的對象。
my_dict={'a':50,'b':60,'c':70,'d':80}
pd.Series(my_dict)
a 50
b 60
c 70
d 80
dtype: int64
#從Series中獲取數據,和字典操作基本一樣。
my_dict['b']
60
#對Series進行算術運算操作
#基於index進行,可以用加減乘除這樣的運算符對兩個Series進行運算。
#結果均以浮點數的形式存儲,以免丟失精度。
series1=pd.Series([1,2,3,4],['shandong','wuhan','changsha','hangzhou'])
series2=pd.Series([4,7,9,2],['beijing','tianjin','shijiazhuang','hangzhou'])
#如果pandas在兩個Series裏找不到相同的index,對應位置就返回空值NaN。
series1-series2
beijing NaN
changsha NaN
hangzhou 2.0
shandong NaN
shijiazhuang NaN
tianjin NaN
wuhan NaN
dtype: float64
series1+series2
beijing NaN
changsha NaN
hangzhou 6.0
shandong NaN
shijiazhuang NaN
tianjin NaN
wuhan NaN
dtype: float64
#DataFrames
#Pandas的DataFrame是一種2維數據結構,數據以表格的形式存儲,分爲若干行和列。
#下面用多個Series來構建一個DataFrame。道理很簡單,多個一維數組組合起來就變成了二維數組
df={'Name':pd.Series(['齊','楚','秦','燕','趙','魏','韓'],index=['東','南','西','東北','北','中北','中']),
'Age':pd.Series(['32','42','32','45','14','22','34'],index=['東','南','西','東北','北','中北','中']),
'size':pd.Series(['2332','4212','3242','4455','1324','2232','3784'],['東','南','西','東北','北','中北','中'])
}
pd.DataFrame(df)
Name Age size
東 齊 32 2332
南 楚 42 4212
西 秦 32 3242
東北 燕 45 4455
北 趙 14 1324
中北 魏 22 2232
中 韓 34 3784
#用一個字典來創建DataFrame
data={'name':['dwd','dwds','fgerd'],
'age':[32,43,1231],
'year':[2012,2123,2312]
}
my_df=pd.DataFrame(data,index=['first','second','last'])
my_df
name age year
first dwd 32 2012
second dwds 43 2123
last fgerd 1231 2312
my_df[['age','year']]
age year
first 32 2012
second 43 2123
last 1231 2312
#給DataFrame增加數據列
#1.可以從頭開始定義一個pd.Series,放到表中.
#2.可以用現有的列來產生需要的新列。
#1
my_df['size']=pd.Series([323,123,435],['first','second','last'])
my_df
name age year size
first dwd 32 2012 323
second dwds 43 2123 123
last fgerd 1231 2312 435
#2從其他列中創造新列
my_df['pip']=my_df['age']+my_df['size']
my_df=pd.DataFrame(my_df)
my_df
name age year size pip
first dwd 32 2012 323 355
second dwds 43 2123 123 166
last fgerd 1231 2312 435 1666
#從DataFrame刪除行/列。用drop()函數。
#使用時需要指定具體的刪除方向,axis=0對應的是行row,axis=1對應的是列column。
my_df.drop('pip',axis=1)
name age year size
first dwd 32 2012 323
second dwds 43 2123 123
last fgerd 1231 2312 435
my_df.drop('first',axis=0)
name age year size pip
second dwds 43 2123 123 166
last fgerd 1231 2312 435 1666
未完待續