文章目錄
要求
1.掌握常見文件格式的讀寫操作
2.理解並熟悉 Series 和 DataFrame 的重要屬性和重要方法
3.掌握各類排序(索引排序和值排序、單級排序和多級排序)
import pandas as pd
import numpy as np
1.查看Pandas版本
pd.__version__
一、文件讀取與寫入
1. 讀取
(a)csv格式
df = pd.read_csv('data/table.csv')
df.head()
(b)txt格式
df_txt = pd.read_table('data/table.txt') #可設置sep分隔符參數
df_txt.head()
(c)xls或xlsx格式
#需要安裝xlrd包
df_excel = pd.read_excel('data/table.xlsx')
df_excel.head()
2. 寫入
(a)csv格式
df.to_csv('data/new_table.csv')
#df.to_csv('data/new_table.csv', index=False) #保存時除去行索引
(b)xls或xlsx格式
#需要安裝openpyxl
df.to_excel('data/new_table2.xlsx', sheet_name='Sheet1')
二、基本數據結構
1. Series
(a)創建一個Series
對於一個Series,其中最常用的屬性爲值(values),索引(index),名字(name),類型(dtype)
s = pd.Series(np.random.randn(5),index=['a','b','c','d','e'],name = '這是一個Series',dtype='float64')
s
(b)訪問Series屬性
s.values
s.name
s.index
(c)取出某一個元素
將在第2章詳細討論索引的應用,這裏先大致瞭解
s['a']
(d)調用方法
s.mean()
Series有相當多的方法可以調用:
print([attr for attr in dir(s) if not attr.startswith('-')])
2. DataFrame
(a)創建一個DataFrame
df = pd.DataFrame({'col1':list('abcde'),'col2':range(5,10),'col3':[1.3,2.5,3.6,4.6,5.8]},
index = list('一二三四五'))
df
(b)從DataFrame取出一列爲Series
df['col1']
type(df)
type(df['col3'])
(c)修改行或列名
df.rename(index={'一':'one'},columns={'col1':'new_col1'})
(d)調用屬性和方法
df.index
df.columns
df.values
df.shape
df.mean()
(e)索引對齊特性
這是Pandas中非常強大的特性,不理解這一特性有時就會造成一些麻煩
df1 = pd.DataFrame({'A':[1,2,3]},index=[1,2,3])
df2 = pd.DataFrame({'A':[1,2,3]},index=[3,1,2])
df1 - df2
(f)列的刪除與添加
對於刪除而言,可以使用drop函數或del或pop
df.drop(index='五',columns='col1')#設置inplace=True後會直接在原DataFrame中改動
df['col1']=[1,2,3,4,5]
del df['col1']
df
pop方法直接在原來的DataFrame上操作,且返回被刪除的列,與python中的pop函數類似
df['col1']=[1,2,3,4,5]
df.pop('col1')
df
可以直接增加新的列,也可以使用assign方法
df1['B']=list('abc')
df1.assign(C=pd.Series(list('def')))
但assign方法不會對原DataFrame做修改
df1
(g)根據類型選擇列
df.select_dtypes(include=['number']).head()
df.select_dtypes(include=['float']).head()
(h)將Series轉換爲DataFrame
s = df.mean()
s.name='to_DataFrame'
s
s.to_frame()
使用T符號可以轉置
s.to_frame().T
三、常用基本函數
從下面開始,包括後面所有章節,我們都會用到這份虛擬的數據集
df = pd.read_csv('data/table.csv')
1. head和tail
df.head()
df.tail()
可以指定n參數顯示多少行
df.head(3)
2. unique和nunique
df['Physics'].nunique()
unique顯示所有的唯一值
df['Physics'].unique()
3. count和value_counts
count返回非缺失值元素個數
df['Physics'].count()
value_counts返回每個元素有多少個
df['Physics'].value_counts()
4. describe和info
info函數返回有哪些列、有多少非缺失值、每列的類型
df.info()
describe默認統計數值型數據的各個統計量
df.describe()
可以自行選擇分位數
df.describe(percentiles=[.05, .25, .75, .95])
對於非數值型也可以用describe函數
df['Physics'].describe()
5. idxmax和nlargest
idxmax函數返回最大值,在某些情況下特別適用,idxmin功能類似
df['Math'].idxmax()
nlargest函數返回前幾個大的元素值,nsmallest功能類似
df['Math'].nlargest(3)
6. clip和replace
clip和replace是兩類替換函數
clip是對超過或者低於某些值的數進行截斷
df['Math'].head()
df['Math'].clip(33,80).head()
df['Math'].mad()
replace是對某些值進行替換
df['Address'].head()
df['Address'].replace(['street_1','street_2'],['one','two']).head()
通過字典,可以直接在表中修改
df.replace({'Address':{'street_1':'one','street_2':'two'}}).head()
7. apply函數
apply是一個自由度很高的函數,在第3章我們還要提到
對於Series,它可以迭代每一列的值操作:
df['Math'].apply(lambda x:str(x)+'!').head() #可以使用lambda表達式,也可以使用函數
對於DataFrame,它可以迭代每一個列操作:
df.apply(lambda x:x.apply(lambda x:str(x)+'!')).head() #這是一個稍顯複雜的例子,有利於理解apply的功能
四、排序
1. 索引排序
df.set_index('Math').head() #set_index函數可以設置索引,將在下一章詳細介紹
df.set_index('Math').sort_index().head() #可以設置ascending參數,默認爲升序,True
2. 值排序
df.sort_values(by='Class').head()
多個值排序,即先對第一層排,在第一層相同的情況下對第二層排序
df.sort_values(by=['Address','Height']).head()
代碼和數據地址:https://github.com/XiangLinPro/pandas
所有巧合的是要麼是上天註定要麼是一個人偷偷的在努力。
公衆號,關注回覆【電子書】有驚喜,資源多多。
個人微信公衆號,專注於學習資源、筆記分享,歡迎關注。我們一起成長,一起學習。一直純真着,善良着,溫情地熱愛生活,,如果覺得有點用的話,請不要吝嗇你手中點讚的權力,謝謝我親愛的讀者朋友。
-Fear not that the life shall come to an end, but rather fear that it shall never have a beginning.——J.H. Newman
「不要害怕你的生活將要結束,應該擔心你的生活永遠不會真正開始。——紐曼」
給大家推薦一個Github,上面非常非常多的乾貨,保證讓你滿意:https://github.com/XiangLinPro/IT_book
關於Datawhale
Datawhale是一個專注於數據科學與AI領域的開源組織,彙集了衆多領域院校和知名企業的優秀學習者,聚合了一羣有開源精神和探索精神的團隊成員。Datawhale以“for the learner,和學習者一起成長”爲願景,鼓勵真實地展現自我、開放包容、互信互助、敢於試錯和勇於擔當。同時Datawhale 用開源的理念去探索開源內容、開源學習和開源方案,賦能人才培養,助力人才成長,建立起人與人,人與知識,人與企業和人與未來的聯結。
2020年4月21日於重慶城口
好好學習,天天向上,終有所獲