首次公开,用了三年的 pandas 速查表!
導讀:Pandas 是一個強大的分析結(jié)構(gòu)化數(shù)據(jù)的工具集,它的使用基礎(chǔ)是 Numpy(提供高性能的矩陣運算),用于數(shù)據(jù)挖掘和數(shù)據(jù)分析,同時也提供數(shù)據(jù)清洗功能。
本文收集了 Python 數(shù)據(jù)分析庫 Pandas 及相關(guān)工具的日常使用方法,備查,持續(xù)更新中。
作者:李慶輝
來源:大數(shù)據(jù)DT(ID:hzdashuju)
縮寫說明:
df:任意的 Pandas DataFrame 對象
s:任意的 Pandas Series 對象
注:有些屬性方法 df 和 s 都可以使用
推薦資源:
pandas 在線教程
https://www.gairuo.com/p/pandas-tutorial
書籍 《深入淺出Pandas:利用Python進行數(shù)據(jù)處理與分析》
01 環(huán)境搭建
#?https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/ #?https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/ #?https://docs.conda.io/en/latest/miniconda.html #?excel?處理相關(guān)包?xlrd?/?openpyxl?/?xlsxwriter #?解析網(wǎng)頁包?requests?/?lxml?/?html5lib?/?BeautifulSoup4 #?計算包:scipy pip?install?jupyter?pandas?matplotlib #?國外網(wǎng)絡(luò)慢,可指定國內(nèi)源快速下載安裝 pip?install?pandas?-i?https://pypi.tuna.tsinghua.edu.cn/simpleConda 多 Python 版本環(huán)境:
#?創(chuàng)建新環(huán)境,<環(huán)境名稱>,?python?版本 conda?create?-n?py39?python=3.9 #?刪除環(huán)境 conda?remove?-n?py39?--all #?進入、激活環(huán)境 conda?activate?py39 #?退出環(huán)境 conda?deactivate #?查看所有虛擬環(huán)境及當前環(huán)境 conda?info?-e02 Jupyter Notebook 快捷鍵
啟動 Jupyter Notebook:jupyter notebook
快捷鍵及功能:
<tab>:代碼提示
Shift+ Enter:執(zhí)行本行并定位到新增的行
Shift+Tab(1-3次):查看函數(shù)方法說明
D, D:雙擊 D 刪除本行
A / B:向上 / 下增加一行
M / Y:Markdown /? 代碼模式
03 導入庫包
import?pandas?as?pd??#?最新為?1.4.1?版本?(2022-02-12) import?numpy?as?np import?matplotlib.pyplot?as?plt import?seaborn?as?sns %matplotlib?inline04 導入數(shù)據(jù)
#?從?CSV?文件導入數(shù)據(jù) pd.read_csv('file.csv',?name=['列名','列名2']) #?從限定分隔符的文本文件導入數(shù)據(jù) pd.read_table(filename,?header=0) #?Excel?導入,指定?sheet?和表頭 pd.read_excel('file.xlsx',?sheet_name='?表1',?header=0) #?從?SQL?表/庫導入數(shù)據(jù) pd.read_sql(query,?connection_object) #?從?JSON?格式的字符串導入數(shù)據(jù) pd.read_json(json_string) #?解析?URL、字符串或者?HTML?文件,抽取其中的?tables?表格 pd.read_html(url) #?從你的粘貼板獲取內(nèi)容,并傳給?read_table() pd.read_clipboard() #?從字典對象導入數(shù)據(jù),Key?是列名,Value是數(shù)據(jù) pd.DataFrame(dict) #?導入字符串 from?io?import?StringIO pd.read_csv(StringIO(web_data.text))05 導出輸出數(shù)據(jù)
#?導出數(shù)據(jù)到CSV文件 df.to_csv('filename.csv') #?導出數(shù)據(jù)到Excel文件 df.to_excel('filename.xlsx',?index=True) #?導出數(shù)據(jù)到?SQL?表 df.to_sql(table_name,?connection_object) #?以Json格式導出數(shù)據(jù)到文本文件 df.to_json(filename) #?其他 df.to_html()??#?顯示?HTML?代碼 df.to_markdown()?#?顯示?markdown?代碼 df.to_string()?#?顯示格式化字符 df.to_latex(index=False)?#?LaTeX?tabular,?longtable df.to_dict('split')?#?字典,?格式?list/series/records/index df.to_clipboard(sep=',',?index=False)?#?存入系統(tǒng)剪貼板#?將兩個表格輸出到一個excel文件里面,導出到多個?sheet writer=pd.ExcelWriter('new.xlsx') df_1.to_excel(writer,sheet_name='第一個',?index=False) df_2.to_excel(writer,sheet_name='第二個',?index=False) writer.save()?#?必須運行writer.save(),不然不能輸出到本地#?寫法2 with?pd.ExcelWriter('new.xlsx')?as?writer:df1.to_excel(writer,?sheet_name='第一個')df2.to_excel(writer,?sheet_name='第二個') #?用?xlsxwriter?導出支持合并單元格、顏色、圖表等定制功能 #?https://xlsxwriter.readthedocs.io/working_with_pandas.html06 創(chuàng)建測試對象
#?創(chuàng)建20行5列的隨機數(shù)組成的?DataFrame?對象 pd.DataFrame(np.random.rand(20,5)) #?從可迭代對象?my_list?創(chuàng)建一個?Series?對象 pd.Series(my_list) #?增加一個日期索引 df.index?=?pd.date_range('1900/1/30',?periods=df.shape[0]) #?創(chuàng)建隨機數(shù)據(jù)集 df?=?pd.util.testing.makeDataFrame() #?創(chuàng)建隨機日期索引數(shù)據(jù)集 df?=?pd.util.testing.makePeriodFrame() df?=?pd.util.testing.makeTimeDataFrame() #?創(chuàng)建隨機混合類型數(shù)據(jù)集 df?=?pd.util.testing.makeMixedDataFrame()07 查看、檢查、統(tǒng)計、屬性
df.head(n)?#?查看?DataFrame?對象的前n行 df.tail(n)?#?查看?DataFrame?對象的最后n行 df.sample(n)?#?查看?n?個樣本,隨機 df.shape?#?查看行數(shù)和列數(shù) df.info()?#?查看索引、數(shù)據(jù)類型和內(nèi)存信息 df.describe()?#?查看數(shù)值型列的匯總統(tǒng)計 df.dtypes?#?查看各字段類型 df.axes?#?顯示數(shù)據(jù)行和列名 df.mean()?#?返回所有列的均值 df.mean(1)?#?返回所有行的均值,下同 df.corr()?#?返回列與列之間的相關(guān)系數(shù) df.count()?#?返回每一列中的非空值的個數(shù) df.max()?#?返回每一列的最大值 df.min()?#?返回每一列的最小值 df.median()?#?返回每一列的中位數(shù) df.std()?#?返回每一列的標準差 df.var()?#?方差 s.mode()?#?眾數(shù) s.prod()?#?連乘 s.cumprod()?#?累積連乘,累乘 df.cumsum(axis=0)?#?累積連加,累加 s.nunique()?#?去重數(shù)量,不同值的量 df.idxmax()?#?每列最大的值的索引名 df.idxmin()?#?最小 df.columns?#?顯示所有列名 df.team.unique()?#?顯示列中的不重復(fù)值 #?查看?Series?對象的唯一值和計數(shù),?計數(shù)占比:?normalize=True s.value_counts(dropna=False) #?查看?DataFrame?對象中每一列的唯一值和計數(shù) df.apply(pd.Series.value_counts) df.duplicated()?#?重復(fù)行 df.drop_duplicates()?#?刪除重復(fù)行 #?set_option、reset_option、describe_option?設(shè)置顯示要求 pd.get_option() #?設(shè)置行列最大顯示數(shù)量,None?為不限制 pd.options.display.max_rows?=?None pd.options.display.max_columns?=?None df.col.argmin()?#?最大值[最小值?.argmax()]?所在位置的自動索引 df.col.idxmin()?#?最大值[最小值?.idxmax()]?所在位置的定義索引 #?累計統(tǒng)計 ds.cumsum()?#?前邊所有值之和 ds.cumprod()?#?前邊所有值之積 ds.cummax()?#?前邊所有值的最大值 ds.cummin()?#?前邊所有值的最小值 #?窗口計算(滾動計算) ds.rolling(x).sum()?#依次計算相鄰x個元素的和 ds.rolling(x).mean()?#依次計算相鄰x個元素的算術(shù)平均 ds.rolling(x).var()?#依次計算相鄰x個元素的方差 ds.rolling(x).std()?#依次計算相鄰x個元素的標準差 ds.rolling(x).min()?#依次計算相鄰x個元素的最小值 ds.rolling(x).max()?#依次計算相鄰x個元素的最大值08 數(shù)據(jù)清理
df.columns?=?['a','b','c']?#?重命名列名 df.columns?=?df.columns.str.replace('?',?'_')?#?列名空格換下劃線 df.loc[df.AAA?>=?5,?['BBB',?'CCC']]?=?555?#?替換數(shù)據(jù) df['pf']?=?df.site_id.map({2:?'小程序',?7:'M?站'})?#?將枚舉換成名稱 pd.isnull()?#?檢查DataFrame對象中的空值,并返回一個?Boolean?數(shù)組 pd.notnull()?#?檢查DataFrame對象中的非空值,并返回一個?Boolean?數(shù)組 df.drop(['name'],?axis=1)?#?刪除列 df.drop([0,?10],?axis=0)?#?刪除行 del?df['name']?#?刪除列 df.dropna()?#?刪除所有包含空值的行 df.dropna(axis=1)?#?刪除所有包含空值的列 df.dropna(axis=1,thresh=n)?#?刪除所有小于?n?個非空值的行 df.fillna(x)?#?用x替換DataFrame對象中所有的空值 df.fillna(value={'prov':'未知'})?#?指定列的空值替換為指定內(nèi)容 s.astype(float)?#?將Series中的數(shù)據(jù)類型更改為?float?類型 df.index.astype('datetime64[ns]')?#?轉(zhuǎn)化為時間格式 s.replace(1,?'one')?#?用?‘one’?代替所有等于?1?的值 s.replace([1,?3],['one','three'])?#?用'one'代替?1,用?'three'?代替?3 df.rename(columns=lambda?x:?x?+?1)?#?批量更改列名 df.rename(columns={'old_name':?'new_name'})?#?選擇性更改列名 df.set_index('column_one')?#?更改索引列 df.rename(index=lambda?x:?x?+?1)?#?批量重命名索引 #?重新命名表頭名稱 df.columns?=?['UID',?'當前待打款金額',?'認證姓名'] df['是否設(shè)置提現(xiàn)賬號']?=?df['狀態(tài)']?#?復(fù)制一列 df.loc[:,?::-1]?#?列順序反轉(zhuǎn) df.loc[::-1]?#?行順序反轉(zhuǎn),?下方為重新定義索引 df.loc[::-1].reset_index(drop=True)09 數(shù)據(jù)處理:Filter、Sort
#?保留小數(shù)位,四舍六入五成雙 df.round(2)?#?全部 df.round({'A':?1,?'C':?2})?#?指定列 df['Name']?=?df.Name?#?取列名的兩個方法 df[df.index?==?'Jude']?#?按索引查詢要用?.index df[df[col]?>?0.5]?#?選擇col列的值大于0.5的行 #?多條件查詢 df[(df['team']?==?'A')?&(?df['Q1']?>?80)?&df.utype.isin(['老客',?'老訪客'])] #?篩選為空的內(nèi)容 df[df.order.isnull()] #?類似?SQL?where?in df[df.team.isin('A','B')] df[(df.team=='B')?&?(df.Q1?==?17)] df[~(df['team']?==?'A')?|?(?df['Q1']?>?80)]?#?非,或 df[df.Name.str.contains('張')]?#?包含字符 df.sort_values(col1)?#?按照列col1排序數(shù)據(jù),默認升序排列 df.col1.sort_values()?#?同上,?->?s df.sort_values(col2,?ascending=False)?#?按照列?col1?降序排列數(shù)據(jù) #?先按列col1升序排列,后按col2降序排列數(shù)據(jù) df.sort_values([col1,col2],?ascending=[True,False]) df2?=?pd.get_dummies(df,?prefix='t_')?#?將枚舉的那些列帶枚舉轉(zhuǎn)到列上 s.set_index().plot() #?多索引處理 dd.set_index(['utype',?'site_id',?'p_day'],?inplace=True) dd.sort_index(inplace=True)?#?按索引排序 dd.loc['新訪客',?2,?'2019-06-22'].plot.barh()?#?loc?中按順序指定索引內(nèi)容 #?前100行, 不能指定行,如:df[100] df[:100] #?只取指定行 df1?=?df.loc[0:,?['設(shè)計師ID',?'姓名']] #?將ages平分成5個區(qū)間并指定?labels ages?=?np.array([1,5,10,40,36,12,58,62,77,89,100,18,20,25,30,32]) pd.cut(ages,?[0,5,20,30,50,100],labels=[u"嬰兒",u"青年",u"中年",u"壯年",u"老年"])daily_index.difference(df_work_day.index)?#?取出差別 #?格式化 df.index.name?#?索引的名稱?str df.columns.tolist() df.values.tolist() df.總?cè)丝?values.tolist() data.apply(np.mean)?#?對?DataFrame?中的每一列應(yīng)用函數(shù)?np.mean data.apply(np.max,axis=1)?#?對?DataFrame?中的每一行應(yīng)用函數(shù)?np.max df.insert(1,?'three',?12,?allow_duplicates=False)?#?插入列?(位置、列名、[值]) df.pop('class')?#?刪除列 #?增加一行 df.append(pd.DataFrame({'one':2,'two':3,'three':?4.4},index=['f']),sort=True) #?指定新列 iris.assign(sepal_ratio=iris['SepalWidth']?/?iris['SepalLength']).head() df.assign(rate=lambda?df:?df.orders/df.uv) #?shift?函數(shù)是對數(shù)據(jù)進行平移動的操作 df['增幅']?=?df['國內(nèi)生產(chǎn)總值']?-?df['國內(nèi)生產(chǎn)總值'].shift(-1) df.tshift(1)?#?時間移動,按周期 #?和上相同,diff?函數(shù)是用來將數(shù)據(jù)進行移動之后與原數(shù)據(jù)差 #?異數(shù)據(jù),等于?df.shift()-df df['增幅']?=?df['國內(nèi)生產(chǎn)總值'].diff(-1) #?留存數(shù)據(jù),因為最大一般為數(shù)據(jù)池 df.apply(lambda?x:?x/x.max(),?axis=1)#?取?best?列中值為列名的值寫到?name?行上 df['value']?=?df.lookup(df['name'],?df['best'])s.where(s?>?1,?10)?#?滿足條件下數(shù)據(jù)替換(10,空為?NaN) s.mask(s?>?0)?#?留下滿足條件的,其他的默認為?NaN #?所有值加?1?(加減乘除等) df?+?1?/?df.add(1) #?管道方法,鏈式調(diào)用函數(shù),f(df)=df.pipe(f) def?gb(df,?by):result?=?df.copy()result?=?result.groupby(by).sum()return?result? #?調(diào)用 df.pipe(gb,?by='team') #?窗口計算?'2s'?為兩秒 df.rolling(2).sum() #?在窗口結(jié)果基礎(chǔ)上的窗口計算 df.expanding(2).sum() #?超出(大于、小于)的值替換成對應(yīng)值 df.clip(-4,?6) #?AB?兩列想加增加?C?列 df['C']?=?df.eval('A+B') #?和上相同效果 df.eval('C?=?A?+?B',?inplace=True) #?數(shù)列的變化百分比 s.pct_change(periods=2) #?分位數(shù),?可實現(xiàn)時間的中間點 df.quantile(.5) #?排名?average,?min,max,first,dense,?默認?average s.rank() #?數(shù)據(jù)爆炸,將本列的類列表數(shù)據(jù)和其他列的數(shù)據(jù)展開鋪開 df.explode('A') #?枚舉更新 status?=?{0:'未執(zhí)行',?1:'執(zhí)行中',?2:'執(zhí)行完畢',?3:'執(zhí)行異常'} df['taskStatus']?=?df['taskStatus'].apply(status.get) df.assign(金額=0)?#?新增字段 df.loc[('bar',?'two'),?'A']?#?多索引查詢 df.query('i0?==?"b"?&?i1?==?"b"')?#?多索引查詢方法?2 #?取多索引中指定級別的所有不重復(fù)值 df.index.get_level_values(2).unique() #?去掉為零小數(shù),12.00?->?12 df.astype('str').applymap(lambda?x:?x.replace('.00',?'')) #?插入數(shù)據(jù),在第三列加入「兩倍」列 df.insert(3,?'兩倍',?df['值']*2) #?枚舉轉(zhuǎn)換 df['gender']?=?df.gender.map({'male':'男',?'female':'女'}) #?增加本行之和列 df['Col_sum']?=?df.apply(lambda?x:?x.sum(),?axis=1) #?對指定行進行加和 col_list=?list(df)[2:]?#?取請假范圍日期 df['總天數(shù)']?=?df[col_list].sum(axis=1)?#?計算總請假天數(shù) #?對列求和,匯總 df.loc['col_sum']?=?df.apply(lambda?x:?x.sum()) #?按指定的列表順序顯示 df.reindex(order_list) #?按指定的多列排序 df.reindex(['col_1',?'col_5'],?axis="columns")10 數(shù)據(jù)選取
df[col]?#?根據(jù)列名,并以Series的形式返回列 df[[col1,?col2]]?#?以DataFrame形式返回多列 df.loc[df['team']?==?'B',['name']]?#?按條件查詢,只顯示name?列 s.iloc[0]?#?按位置選取數(shù)據(jù) s.loc['index_one']?#?按索引選取數(shù)據(jù) df.loc[0,'A':'B']?#??A到?B?字段的第一行? df.loc[2018:1990,?'第一產(chǎn)業(yè)增加值':'第三產(chǎn)業(yè)增加值'] df.loc[0,['A','B']]?#?d.loc[位置切片,?字段] df.iloc[0,:]?#?返回第一行,?iloc?只能是數(shù)字 df.iloc[0,0]?#?返回第一列的第一個元素 dc.query('site_id?>?8?and?utype=="老客"').head()?#?可以?and?or?/?&?|#?迭代器及使用 for?idx,row?in?df.iterrows():?row['id'] #?迭代器對每個元素進行處理 df.loc[i,'鏈接']?=?f'http://www.gairuo.com/p/{slug}.html' for?i?in?df.Name:print(i)?#?迭代一個列 #?按列迭代,[列名,?列中的數(shù)據(jù)序列?S(索引名?值)] for?label,?content?in?df.items():print(label,?content) #?按行迭代,迭代出整行包括索引的類似列表的內(nèi)容,可row[2]取 for?row?in?df.itertuples():print(row) df.at[2018,?'總?cè)丝?#39;]?#?按行列索引名取一個指定的單個元素 df.iat[1,?2]?#?索引和列的編號取單個元素 s.nlargest(5).nsmallest(2)?#?最大和最小的前幾個值 df.nlargest(3,?['population',?'GDP']) df.take([0,?3])?#?指定多個行列位置的內(nèi)容 #?按行列截取掉部分內(nèi)容,支持日期索引標簽 ds.truncate(before=2,?after=4) #?將?dataframe?轉(zhuǎn)成?series df.iloc[:,0] float(str(val).rstrip('%'))?#?百分數(shù)轉(zhuǎn)數(shù)字 df.reset_index(inplace=True)?#?取消索引11 數(shù)據(jù)處理 GroupBy 透視
df.groupby(col)?#?返回一個按列col進行分組的Groupby對象 df.groupby([col1,col2])?#?返回一個按多列進行分組的Groupby對象 df.groupby(col1)[col2]?#?返回按列col1進行分組后,列col2的均值 #?創(chuàng)建一個按列col1進行分組,并計算col2和col3的最大值的數(shù)據(jù)透視表 df.pivot_table(index=col1,values=[col2,col3],aggfunc=max,as_index=False) #?同上 df.pivot_table(index=['site_id',?'utype'],values=['uv_all',?'regist_num'],aggfunc=['max',?'mean']) df.groupby(col1).agg(np.mean)?#?返回按列col1分組的所有列的均值 #?按列將其他列轉(zhuǎn)行 pd.melt(df,?id_vars=["day"],?var_name='city',?value_name='temperature') #?交叉表是用于統(tǒng)計分組頻率的特殊透視表 pd.crosstab(df.Nationality,df.Handedness) #?groupby?后排序,分組?agg?內(nèi)的元素取固定個數(shù) (df[(df.p_day?>=?'20190101')].groupby(['p_day',?'name']).agg({'uv':sum}).sort_values(['p_day','uv'],?ascending=[False,?False]).groupby(level=0).head(5)?#?每天取5個頁面.unstack().plot() ) #?合并查詢經(jīng)第一個看(max,?min,?last,?size:數(shù)量) df.groupby('結(jié)算類型').first() #?合并明細并分組統(tǒng)計加總('max',?`mean`,?`median`, #?`prod`,?`sum`,?`std`,`var`,?'nunique'),'nunique'為去重的列表 df1?=?df.groupby(by='設(shè)計師ID').agg({'結(jié)算金額':sum}) df.groupby(by=df.pf).ip.nunique()?#?groupby?distinct,?分組+去重數(shù) df.groupby(by=df.pf).ip.value_counts()?#?groupby?分組+去重的值及數(shù)量 df.groupby('name').agg(['sum',?'median',?'count'])12 數(shù)據(jù)合并
#?合并拼接行 #?將df2中的行添加到df1的尾部 df1.append(df2) #?指定列合并成一個新表新列 ndf?=?(df['提名1'].append(df['提名2'],?ignore_index=True).append(df['提名3'],?ignore_index=True)) ndf?=?pd.DataFrame(ndf,?columns=(['姓名'])) #?將df2中的列添加到df1的尾部 df.concat([df1,?df2],?axis=1)#?合并文件的各行 df1?=?pd.read_csv('111.csv',?sep='\t') df2?=?pd.read_csv('222.csv',?sep='\t') excel_list?=?[df1,?df2] #?result?=?pd.concat(excel_list).fillna('')[:].astype('str') result?=?pd.concat(excel_list)[] result.to_excel('333.xlsx',?index=False)#?合并指定目錄下所有的?excel?(csv)?文件 import?glob files?=?glob.glob("data/cs/*.xls") dflist?=?[] for?i?in?files:dflist.append(pd.read_excel(i,?usecols=['ID',?'時間',?'名稱']))df?=?pd.concat(dflist)#?合并增加列 #?對df1的列和df2的列執(zhí)行SQL形式的join df1.join(df2,on=col1,how='inner') #?用?key?合并兩個表 df_all?=?pd.merge(df_sku,?df_spu,?how='left',left_on=df_sku['product_id'],right_on=df_spu['p.product_id'])13 時間處理 時間序列
#?時間索引 df.index?=?pd.DatetimeIndex(df.index) #?時間只保留日期 df['date']?=?df['time'].dt.date #?將指定字段格式化為時間類型 df["date"]?=?pd.to_datetime(df['時間']) #?轉(zhuǎn)化為北京時間 df['time']?=?df['time'].dt.tz_convert('Asia/Shanghai') #?轉(zhuǎn)為指定格式,可能會失去秒以后的精度 df['time']?=?df['time'].dt.strftime("%Y-%m-%d?%H:%M:%S") dc.index?=?pd.to_datetime(dc.index,?format='%Y%m%d',?errors='ignore') #?時間,參與運算 pd.DateOffset(days=2) #?當前時間 pd.Timestamp.now() pd.to_datetime('today') #?判斷時間是否當天 pd.datetime.today().year?==?df.start_work.dt.year df.time.astype('datetime64[ns]').dt.date?==?pd.to_datetime('today') #?定義個天數(shù) import?datetime days?=?lambda?x:?datetime.timedelta(days=x) days(2) #?同上,直接用?pd?包裝的 pd.Timedelta(days=2) #?unix?時間戳 pd.to_datetime(ted.film_date,?unit='ms') #?按月(YMDHminS)采集合計數(shù)據(jù) df.set_index('date').resample('M')['quantity'].sum() df.set_index('date').groupby('name')['ext?price'].resample("M").sum() #?按天匯總,index?是?datetime?時間類型 df.groupby(by=df.index.date).agg({'uu':'count'}) #?按周匯總 df.groupby(by=df.index.weekday).uu.count() #?按月進行匯總 df.groupby(['name',?pd.Grouper(key='date',?freq='M')])['ext?price'].sum() #?按月進行匯總 df.groupby(pd.Grouper(key='day',?freq='1M')).sum() #?按照年度,且截止到12月最后一天統(tǒng)計?ext?price?的?sum?值 df.groupby(['name',?pd.Grouper(key='date',?freq='A-DEC')])['ext?price'].sum() #?按月的平均重新采樣 df['Close'].resample('M').mean() #?https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases #?取時間范圍,并取工作日 rng?=?pd.date_range(start="6/1/2016",end="6/30/2016",freq='B') #?重新定時數(shù)據(jù)頻度,按一定補充方法 df.asfreq('D',?method='pad') #?時區(qū),df.tz_convert('Europe/Berlin') df.time.tz_localize(tz='Asia/Shanghai') #?轉(zhuǎn)北京時間 df['Time']?=?df['Time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Shanghai') #?查看所有時區(qū) from?pytz?import?all_timezones print?(all_timezones) #?時長,多久,兩個時間間隔時間,時差 df['duration']?=?pd.to_datetime(df['end'])?-?pd.to_datetime(df['begin']) #?指定時間進行對比 df.Time.astype('datetime64[ns]')?<?pd.to_datetime('2019-12-11?20:00:00',?format='%Y-%m-%d?%H:%M:%S')14 常用備忘
#?解決科學計數(shù)法問題 df?=?pd.read_csv('111.csv',?sep='\t').fillna('')[:].astype('str') #?和訂單量相關(guān)性最大到小顯示 dd.corr().total_order_num.sort_values(ascending=False)#?解析列表、json?字符串 import?ast ast.literal_eval("[{'id':?7,?'name':?'Funny'}]")#?Series?apply?method?applies?a?function?to #?every?element?in?a?Series?and?returns?a?Series ted.ratings.apply(str_to_list).head() #?lambda?is?a?shorter?alternative ted.ratings.apply(lambda?x:?ast.literal_eval(x)) #?an?even?shorter?alternative?is?to?apply?the? #?function?directly?(without?lambda) ted.ratings.apply(ast.literal_eval) #?索引?index?使用?apply() df.index.to_series().apply()15 樣式顯示
#?https://pbpython.com/styling-pandas.html df['per_cost']?=?df['per_cost'].map('{:,.2f}%'.format)??#?顯示%比形式 #?指定列表(值大于0)加背景色 df.style.applymap(lambda?x:?'background-color:?grey'?if?x>0?else?'',subset=pd.IndexSlice[:,?['B',?'C']])#?最大值最小值加背景色 df.style.highlight_max(color='lightgreen').highlight_min(color='#cd4f39') df.style.format('{:.2%}',?subset=pd.IndexSlice[:,?['B']])?#?顯示百分號#?指定各列的樣式 format_dict?=?{'sum':'${0:,.0f}','date':?'{:%Y-%m}','pct_of_total':?'{:.2%}''c':?str.upper}#?一次性樣式設(shè)置 (df.style.format(format_dict)?#?多種樣式形式.hide_index()#?指定列按顏色深度表示值大小,?cmap?為?matplotlib?colormap.background_gradient(subset=['sum_num'],?cmap='BuGn')#?表格內(nèi)作橫向?bar?代表值大小.bar(color='#FFA07A',?vmin=100_000,?subset=['sum'],?align='zero')#?表格內(nèi)作橫向?bar?代表值大小.bar(color='lightgreen',?vmin=0,?subset=['pct_of_total'],?align='zero')#?下降(小于0)為紅色,?上升為綠色.bar(color=['#ffe4e4','#bbf9ce'],?vmin=0,?vmax=1,?subset=['增長率'],?align='zero')#?給樣式表格起個名字.set_caption('2018?Sales?Performance').hide_index())#?按條件給整行加背景色(樣式) def?background_color(row):if?row.pv_num?>=?10000:return?['background-color:?red']?*?len(row)elif?row.pv_num?>=?100:return?['background-color:?yellow']?*?len(row)return?['']?*?len(row) #?使用 df.style.apply(background_color,?axis=1)16 表格中的直方圖,sparkline 圖形
import?sparklines import?numpy?as?np def?sparkline_str(x):bins=np.histogram(x)[0]sl?=?''.join(sparklines.sparklines(bins))return?sl sparkline_str.__name__?=?"sparkline" #?畫出趨勢圖,保留兩位小數(shù) df.groupby('name')['quantity',?'ext?price'].agg(['mean',?sparkline_str]).round(2)#?sparkline?圖形 #?https://hugoworld.wordpress.com/2019/01/26/sparklines-in-jupyter-notebooks-ipython-and-pandas/ def?sparkline(data,?figsize=(4,?0.25),?**kwargs):"""creates?a?sparkline"""#?Turn?off?the?max?column?width?so?the?images?won't?be?truncatedpd.set_option('display.max_colwidth',?-1)#?Turning?off?the?max?column?will?display?all?the?data#?if?gathering?into?sets?/?array?we?might?want?to?restrict?to?a?few?itemspd.set_option('display.max_seq_items',?3)#Monkey?patch?the?dataframe?so?the?sparklines?are?displayedpd.DataFrame._repr_html_?=?lambda?self:?self.to_html(escape=False)from?matplotlib?import?pyplot?as?pltimport?base64from?io?import?BytesIOdata?=?list(data)*_,?ax?=?plt.subplots(1,?1,?figsize=figsize,?**kwargs)ax.plot(data)ax.fill_between(range(len(data)),?data,?len(data)*[min(data)],?alpha=0.1)ax.set_axis_off()img?=?BytesIO()plt.savefig(img)plt.close()return?'<img?src="data:image/png;base64,?{}"?/>'.format(base64.b64encode(img.getvalue()).decode())#?使用 df.groupby('name')['quantity',?'ext?price'].agg(['mean',?sparkline]) df.apply(sparkline,?axis=1)?#?僅支持橫向數(shù)據(jù)畫線,可做?T?轉(zhuǎn)置17 可視化
kind : str
'line' : line plot (default)
'bar' : vertical bar plot
'barh' : horizontal bar plot
'hist' : histogram
'box' : boxplot
'kde' : Kernel Density Estimation plot
'density' : same as 'kde'
'area' : area plot
'pie' : pie plot
常用方法:
18 Jupyter notebooks 問題
#?jupyter?notebooks?plt?圖表配置 import?matplotlib.pyplot?as?plt plt.rcParams['figure.figsize']?=?(15.0,?8.0)?#?固定顯示大小 plt.rcParams['font.family']?=?['sans-serif']?#?顯示中文問題 plt.rcParams['font.sans-serif']?=?['SimHei']?#?顯示中文問題#?輸出單行全部變量 from?IPython.core.interactiveshell?import?InteractiveShell InteractiveShell.ast_node_interactivity?=?'all'#?jupyter?notebooks?頁面自適應(yīng)寬度 from?IPython.core.display?import?display,?HTML display(HTML("<style>.container?{?width:100%?!important;?}</style>")) #?背景白色?<style>#notebook_panel?{background:?#ffffff;}</style>#?jupyter?notebooks?嵌入頁面內(nèi)容 from?IPython.display?import?IFrame IFrame('https://arxiv.org/pdf/1406.2661.pdf',?width=800,?height=450)#?Markdown?一個?cell?不支持多張粘貼圖片 #?一個文件打印打開只顯示一張圖片問題解決 #?/site-packages/notebook/static/notebook/js/main.min.js?var?key?處 #?33502、33504?行 key?=?utils.uuid().slice(2,6)+encodeURIandParens(blob.name); key?=?utils.uuid().slice(2,6)+Object.keys(that.attachments).length; #?https://github.com/ihnorton/notebook/commit/55687c2dc08817da587977cb6f19f8cc0103bab1#?多行輸出 from?IPython.core.interactiveshell?import?InteractiveShell InteractiveShell.ast_node_interactivity?=?'all'?#默認為'last'#?執(zhí)行?shell?命令:?!?<命令語句>#?在線可視化工具 https://plot.ly/create19 Slideshow 幻燈片
安裝 RISE 庫:pip install RISE
[Alt+r]?播放/退出播放
「,」逗號隱藏左側(cè)兩個大操作按鈕,「t」總覽?ppt,「/」黑屏
Slide:主頁面,通過按左右方向鍵進行切換。
Sub-Slide:副頁面,通過按上下方向鍵進行切換。全屏
Fragment:一開始是隱藏的,按空格鍵或方向鍵后顯示,實現(xiàn)動態(tài)效果。在一個頁面
Skip:在幻燈片中不顯示的單元。
Notes:作為演講者的備忘筆記,也不在幻燈片中顯示。
關(guān)于作者:李慶輝,數(shù)據(jù)產(chǎn)品專家,某電商公司數(shù)據(jù)產(chǎn)品團隊負責人,擅長通過數(shù)據(jù)治理、數(shù)據(jù)分析、數(shù)據(jù)化運營提升公司的數(shù)據(jù)應(yīng)用水平。?
精通Python數(shù)據(jù)科學及Python Web開發(fā),曾獨立開發(fā)公司的自動化數(shù)據(jù)分析平臺,參與教育部“1+X”數(shù)據(jù)分析(Python)職業(yè)技能等級標準評審。?
中國人工智能學會會員,企業(yè)數(shù)字化、數(shù)據(jù)產(chǎn)品和數(shù)據(jù)分析講師,在個人網(wǎng)站“蓋若”上編寫的技術(shù)和產(chǎn)品教程廣受歡迎。
延伸閱讀👇
《深入淺出Pandas》
點擊上圖了解及購買
轉(zhuǎn)載請聯(lián)系微信:DoctorData
推薦語:這是一本全面覆蓋了Pandas使用者的普遍需求和痛點的著作,基于實用、易學的原則,從功能、使用、原理等多個維度對Pandas做了全方位的詳細講解,既是初學者系統(tǒng)學習Pandas難得的入門書,又是有經(jīng)驗的Python工程師案頭必不可少的查詢手冊。?
李慶輝老師在線答疑群👇
在線提交問題文檔,作者逐一答疑,手把手教你學Pandas。
以下是部分讀者的答疑情況,歡迎購買本書的讀者添加微信 zj06220_0(備注:Pandas)入群。
據(jù)統(tǒng)計,99%的大咖都關(guān)注了這個公眾號
👇
總結(jié)
以上是生活随笔為你收集整理的首次公开,用了三年的 pandas 速查表!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#、.Net经典面试题集锦(一)
- 下一篇: linux使用手记