Datawhale學習
作者:楊煜,Datawhale成員
寄語:本文對Pandas基礎(chǔ)內(nèi)容進行了梳理,從文件讀取與寫入、Series及DataFrame基本數(shù)據(jù)結(jié)構(gòu)、常用基本函數(shù)及排序四個模塊快速入門。
完整學習教程已開源,開源鏈接:
https://github.com/datawhalechina/joyful-pandas
import pandas as pd
import numpy as np
# 加上這兩行可以一次性輸出多個變量而不用print
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'
# 查看版本
pd.__version__
pd.set_option('display.max_columns', None)
Pandas常用的有以下三種文件:
csv文件
txt文件
xls/xlsx文件
讀取文件時的注意事項:
文件路徑是否正確,相對路徑 ./data
編碼方式 分隔符
列名
#讀取csv文件
df = pd.read_csv('./data./table.csv')
df.head()
#讀取txt文件,直接讀取可能會出現(xiàn)數(shù)據(jù)都擠在一列上
df_txt = pd.read_table('./data./table.txt')
#df_txt = pd.read_table('./data./table.csv', sep=',')
df_txt.head()
#讀取xls/xlsx文件
df_excel = pd.read_excel('./data./table.xlsx')
df_excel.head()
寫入
將結(jié)果輸出到csx、txt、xls、xlsx文件中
df.to_csv('./new table.csv')
df.to_excel('./new table.xlsx')
1. 創(chuàng)建
s = pd.Series(np.random.randn(5), index=['a','b','c','d','e'],
name='this is a series', dtype='float64')
2. 訪問Series屬性
s.values, s.index, s.name, s.dtype
3. 取出某元素
通過索引取數(shù)或通過位置取數(shù)
s['a'], s[2:], s[1]
4. 調(diào)用方法
s.mean(), s.sum(), s.hist()
DataFrame基本屬性有 values、columns、index
df = pd.DataFrame({'col1':list('abcde'), 'col2':range(5,10),
'col3':[1.3,2.5,3.6,4.6,5.8]}, index=list('一二三四五'))
2. 取一列/取一行
df['col1'], df[:1]
type(df), type(df['col1']), type(df[:1]
3. 修改行或列名
df.rename(index={'一':'one'}, columns={'col1':'new_col1'})
4. 調(diào)用屬性和方法
df.index, df.columns, df.values, df.shape, df.mean()
5. 索引對齊特性
df1 = pd.DataFrame({'A':[1,2,3]},index=[1,2,3])
df2 = pd.DataFrame({'A':[1,2,3]},index=[3,1,2])
df1-df2 #由于索引對齊,因此結(jié)果不是0
6. 列的刪除
對于刪除而言,可以使用drop函數(shù)或del或pop。
方法1:直接drop不會影響原DataFrame,設(shè)置inplace=True后會直接在原DataFrame中改動;
df.drop(index='五', columns='col1')
方法2:del會直接改變原Dataframe;
df['col1']=[1,2,3,4,5]
del df['col1']
方法3:pop方法直接在原來的DataFrame上操作,且返回被刪除的列,與python中的pop函數(shù)類。
df['col1']=[1,2,3,4,5]
df.pop('col1')
7. 列的添加
方法1:直接新增;
df1['B'] = list('abc')
方法2:用assign方法,不會改變原DataFrame;
df1.assign(C=pd.Series(list('def')))
方法3:df.assign 效果其實是左連接,之所以會出現(xiàn)NaN的情況,是因為C和df的索引不一致導致。打印一下可以看到,df的索引是1-3,而C默認的是0-4。
C=pd.Series(list('def'))
8. 根據(jù)類型選擇列
df.select_dtypes(include=['number'])
df.select_dtypes(include=['float'])
1. DataFrame轉(zhuǎn)換為Series
就是取某一列的操作
s = df.mean()
s.name = 'to_DataFrame'
2. Series轉(zhuǎn)換為DataFrame
使用to_frame() 方法
s.to_frame()
# T符號可以進行轉(zhuǎn)置操作
s.to_frame().T
首先,讀取數(shù)據(jù)
df = pd.read_csv('./data/table.csv')
1. head & tail
用來顯示數(shù)據(jù)頭部或者尾部的幾行數(shù)據(jù),默認是5行。可以指定n參數(shù)顯示多少行
df.head()
df.tail()
df.head(6)
unique顯示所有的唯一值是什么;nunique顯示有多少個唯一值。需要注意的是:需要在具體列上操作,本身DataFrame并沒有這兩個方法
df['Physics'].unique()
df['Physics'].nunique()
count返回非缺失值元素個數(shù);value_counts返回每個元素有多少個值,也是作用在具體某列上
df['Physics'].count()
df['Physics'].value_counts()
info() 函數(shù)返回有哪些列、有多少非缺失值、每列的類型;describe() 默認統(tǒng)計數(shù)值型數(shù)據(jù)的各個統(tǒng)計量,可以自行選擇分位數(shù)位置。非數(shù)值型特征需要單獨調(diào)用describe方法。
df.info()
df.describe()
# describe()可以自行選擇分位數(shù)位置
df.describe(percentiles=[.05, .25, .75, .95])
# 非數(shù)值型特征需要單獨調(diào)用describe方法
df['Physics'].describe()
idxmax函數(shù)返回最大值對應(yīng)的索引,在某些情況下特別適用,idxmin功能類似;nlargest函數(shù)返回前幾個大的元素值,nsmallest功能類似,需要指定具體列
df['Math'].idxmax()
df['Math'].max()
df['Math'].nlargest(2)
clip和replace是兩類替換函數(shù):
clip是對超過或者低于某些值的數(shù)進行截斷,numpy.clip(a, a_min, a_max, out=None)
replace是對某些值進行替換
df['Math'].head()
# 低于33的全都顯示為33, 高于80的全都顯示為80
df['Math'].clip(33,80).head()
df['Math'].mad()
df['Address'].head()
df['Address'].replace(['street_1','street_2'],['one','two']).head()
# 還可以通過字典方式修改
df.replace({'Address':{'street_1':'one','street_2':'two'}}).head(
apply和匿名函數(shù) lambda結(jié)合使用,可以很方便的進行一些數(shù)據(jù)處理。對于Series,它可以迭代每一列的值(行)操作;對于DataFrame,它可以迭代每一個列操作。
# 遍歷Math列中的所有值,添加!
df['Math'].apply(lambda x:str(x)+'!').head()
# 先是遍歷所有列,然后遍歷每列的所有的值,添加!
df.apply(lambda x:x.apply(lambda x:str(x)+'!')).head()
1. 索引排序
#set_index函數(shù)可以設(shè)置索引,將在下一章詳細介紹
df.set_index('Math').head()
#可以設(shè)置ascending參數(shù),默認為升序,True
df.set_index('Math').sort_index().head()
2. 值排序
df.sort_values(by='Class').head()
df.sort_values(by=['Address','Height']).head()
問題
1. Series和DataFrame有哪些常見屬性和方法?
Series
屬性方法 | 說明 |
s.values | 訪問s的內(nèi)容 |
s.index | 獲取s的索引 |
s.iteritems() | 獲取索引和值對 |
s.dtype | 獲取s的數(shù)據(jù)類型 |
s[‘a(chǎn)’] | 根據(jù)索引訪問元素 |
DataFrame
屬性方法 | 說明 |
df.index | 訪問行索引 |
df.columns | 訪問列索引 |
df.values | 訪問數(shù)據(jù) |
df.shape | 獲取df的數(shù)據(jù)形狀 |
2. value_counts會統(tǒng)計缺失值嗎?
答:value_counts不會統(tǒng)計缺失值。
3. 與idxmax和nlargest功能相反的是哪兩組函數(shù)?
答:idxmin和nsmallest。
4. 在常用函數(shù)一節(jié)中,由于一些函數(shù)的功能比較簡單,因此沒有列入,現(xiàn)在將它們列在下面,請分別說明它們的用途并嘗試使用。
5. df.mean(axis=1)是什么意思?它與df.mean()的結(jié)果一樣嗎?第一問提到的函數(shù)也有axis參數(shù)嗎?怎么使用?
答:df.mean(axis=1)意思是對df按列求均值;axis = 0表示保持列標簽不變,對行進行操作;axis = 1表示保持行標簽不變,對列進行操作。