Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
andas是一個Python語言的軟件包,在我們使用Python語言進(jìn)行機(jī)器學(xué)習(xí)編程的時候,這是一個非常常用的基礎(chǔ)編程庫。本文是對它的一個入門教程。
pandas提供了快速,靈活和富有表現(xiàn)力的數(shù)據(jù)結(jié)構(gòu),目的是使“關(guān)系”或“標(biāo)記”數(shù)據(jù)的工作既簡單又直觀。它旨在成為在Python中進(jìn)行實(shí)際數(shù)據(jù)分析的高級構(gòu)建塊。
pandas適合于許多不同類型的數(shù)據(jù),包括:
由于這是一個Python語言的軟件包,因此需要你的機(jī)器上首先需要具備Python語言的環(huán)境。關(guān)于這一點(diǎn),請自行在網(wǎng)絡(luò)上搜索獲取方法。
關(guān)于如何獲取pandas請參閱官網(wǎng)上的說明:pandas Installation(http://pandas.pydata.org/pandas-docs/stable/install.html?spm=a2c4e.11153940.blogcont596296.14.67e04526nmEaeg)。
通常情況下,我們可以通過pip來執(zhí)行安裝:
sudo pip3 install pandas
或者通過conda(http://pandas.pydata.org/pandas-docs/stable/install.html?spm=a2c4e.11153940.blogcont596296.15.67e04526nmEaeg#installing-pandas-with-anaconda) 來安裝pandas:
conda install pandas
目前(2018年2月)pandas的最新版本是v0.22.0(http://pandas.pydata.org/pandas-docs/stable/whatsnew.html?spm=a2c4e.11153940.blogcont596296.16.67e04526nmEaeg#v0-22-0-december-29-2017)(發(fā)布時間:2017年12月29日)。
我已經(jīng)將本文的源碼和測試數(shù)據(jù)放到Github上: pandas_tutorial(https://github.com/paulQuei/pandas_tutorial?spm=a2c4e.11153940.blogcont596296.17.67e04526nmEaeg) ,讀者可以前往獲取。
另外,pandas常常和NumPy一起使用,本文中的源碼中也會用到NumPy(http://www.numpy.org/?spm=a2c4e.11153940.blogcont596296.18.67e04526nmEaeg)。
建議讀者先對NumPy有一定的熟悉再來學(xué)習(xí)pandas。
pandas最核心的就是Series和DataFrame兩個數(shù)據(jù)結(jié)構(gòu)。
這兩種類型的數(shù)據(jù)結(jié)構(gòu)對比如下:
DataFrame可以看做是Series的容器,即:一個DataFrame中可以包含若干個Series。
注:在0.20.0版本之前,還有一個三維的數(shù)據(jù)結(jié)構(gòu),名稱為Panel。這也是pandas庫取名的原因:pan(el)-da(ta)-s。但這種數(shù)據(jù)結(jié)構(gòu)由于很少被使用到,因此已經(jīng)被廢棄了。
Series
由于Series是一維結(jié)構(gòu)的數(shù)據(jù),我們可以直接通過數(shù)組來創(chuàng)建這種數(shù)據(jù),像這樣:
# data_structure.py import pandas as pd import numpy as np series1=pd.Series([1, 2, 3, 4]) print("series1:\n{}\n".format(series1))
這段代碼輸出如下:
series1: 0 1 1 2 2 3 3 4 dtype: int64
這段輸出說明如下:
我們可以分別打印出Series中的數(shù)據(jù)和索引:
# data_structure.py print("series1.values: {}\n".format(series1.values)) print("series1.index: {}\n".format(series1.index))
這兩行代碼輸出如下:
series1.values: [1 2 3 4] series1.index: RangeIndex(start=0, stop=4, step=1)
如果不指定(像上面這樣),索引是[1, N-1]的形式。不過我們也可以在創(chuàng)建Series的時候指定索引。索引未必一定需要是整數(shù),可以是任何類型的數(shù)據(jù),例如字符串。例如我們以七個字母來映射七個音符。索引的目的是可以通過它來獲取對應(yīng)的數(shù)據(jù),例如下面這樣:
# data_structure.py series2=pd.Series([1, 2, 3, 4, 5, 6, 7], index=["C", "D", "E", "F", "G", "A", "B"]) print("series2:\n{}\n".format(series2)) print("E is {}\n".format(series2["E"]))
這段代碼輸出如下:
series2: C 1 D 2 E 3 F 4 G 5 A 6 B 7 dtype: int64 E is 3
DataFrame
下面我們來看一下DataFrame的創(chuàng)建。我們可以通過NumPy的接口來創(chuàng)建一個4x4的矩陣,以此來創(chuàng)建一個DataFrame,像這樣:
# data_structure.py df1=pd.DataFrame(np.arange(16).reshape(4,4)) print("df1:\n{}\n".format(df1))
這段代碼輸出如下:
df1: 0 1 2 3 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 3 12 13 14 15
從這個輸出我們可以看到,默認(rèn)的索引和列名都是[0, N-1]的形式。
我們可以在創(chuàng)建DataFrame的時候指定列名和索引,像這樣:
# data_structure.py df2=pd.DataFrame(np.arange(16).reshape(4,4), columns=["column1", "column2", "column3", "column4"], index=["a", "b", "c", "d"]) print("df2:\n{}\n".format(df2))
這段代碼輸出如下:
df2: column1 column2 column3 column4 a 0 1 2 3 b 4 5 6 7 c 8 9 10 11 d 12 13 14 15
我們也可以直接指定列數(shù)據(jù)來創(chuàng)建DataFrame:
# data_structure.py df3=pd.DataFrame({"note" : ["C", "D", "E", "F", "G", "A", "B"], "weekday": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]}) print("df3:\n{}\n".format(df3))
這段代碼輸出如下:
df3: note weekday 0 C Mon 1 D Tue 2 E Wed 3 F Thu 4 G Fri 5 A Sat 6 B Sun
請注意:
例如:
# data_structure.py noteSeries=pd.Series(["C", "D", "E", "F", "G", "A", "B"], index=[1, 2, 3, 4, 5, 6, 7]) weekdaySeries=pd.Series(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], index=[1, 2, 3, 4, 5, 6, 7]) df4=pd.DataFrame([noteSeries, weekdaySeries]) print("df4:\n{}\n".format(df4))
df4的輸出如下:
df4: 1 2 3 4 5 6 7 0 C D E F G A B 1 Mon Tue Wed Thu Fri Sat Sun
我們可以通過下面的形式給DataFrame添加或者刪除列數(shù)據(jù):
# data_structure.py df3["No."]=pd.Series([1, 2, 3, 4, 5, 6, 7]) print("df3:\n{}\n".format(df3)) del df3["weekday"] print("df3:\n{}\n".format(df3))
這段代碼輸出如下:
df3: note weekday No. 0 C Mon 1 1 D Tue 2 2 E Wed 3 3 F Thu 4 4 G Fri 5 5 A Sat 6 6 B Sun 7 df3: note No. 0 C 1 1 D 2 2 E 3 3 F 4 4 G 5 5 A 6 6 B 7
Index對象與數(shù)據(jù)訪問
pandas的Index對象包含了描述軸的元數(shù)據(jù)信息。當(dāng)創(chuàng)建Series或者DataFrame的時候,標(biāo)簽的數(shù)組或者序列會被轉(zhuǎn)換成Index。可以通過下面的方式獲取到DataFrame的列和行的Index對象:
# data_structure.py print("df3.columns\n{}\n".format(df3.columns)) print("df3.index\n{}\n".format(df3.index))
這兩行代碼輸出如下:
df3.columns Index(['note', 'No.'], dtype='object') df3.index RangeIndex(start=0, stop=7, step=1)
請注意:
DataFrame提供了下面兩個操作符來訪問其中的數(shù)據(jù):
例如這樣:
# data_structure.py print("Note C, D is:\n{}\n".format(df3.loc[[0, 1], "note"])) print("Note C, D is:\n{}\n".format(df3.iloc[[0, 1], 0]))
第一行代碼訪問了行索引為0和1,列索引為“note”的元素。第二行代碼訪問了行下標(biāo)為0和1(對于df3來說,行索引和行下標(biāo)剛好是一樣的,所以這里都是0和1,但它們卻是不同的含義),列下標(biāo)為0的元素。
這兩行代碼輸出如下:
Note C, D is: 0 C 1 D Name: note, dtype: object Note C, D is: 0 C 1 D Name: note, dtype: object
pandas庫提供了一系列的read_函數(shù)來讀取各種格式的文件,它們?nèi)缦滤荆?/p>
讀取Excel文件
注:要讀取Excel文件,還需要安裝另外一個庫:xlrd
通過pip可以這樣完成安裝:
sudo pip3 install xlrd
安裝完之后可以通過pip查看這個庫的信息:
$ pip3 show xlrd Name: xlrd Version: 1.1.0 Summary: Library for developers to extract data from Microsoft Excel (tm) spreadsheet files Home-page: http://www.python-excel.org/ Author: John Machin Author-email: sjmachin@lexicon.net License: BSD Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages Requires:
接下來我們看一個讀取Excel的簡單的例子:
# file_operation.py import pandas as pd import numpy as np df1=pd.read_excel("data/test.xlsx") print("df1:\n{}\n".format(df1))
這個Excel的內(nèi)容如下:
df1: C Mon 0 D Tue 1 E Wed 2 F Thu 3 G Fri 4 A Sat 5 B Sun
注:本文的代碼和數(shù)據(jù)文件可以通過文章開頭提到的Github倉庫獲取。
讀取CSV文件
下面,我們再來看讀取CSV文件的例子。
第一個CSV文件內(nèi)容如下:
$ cat test1.csv C,Mon D,Tue E,Wed F,Thu G,Fri A,Sat
讀取的方式也很簡單:
# file_operation.py df2=pd.read_csv("data/test1.csv") print("df2:\n{}\n".format(df2))
我們再來看第2個例子,這個文件的內(nèi)容如下:
$ cat test2.csv C|Mon D|Tue E|Wed F|Thu G|Fri A|Sat
嚴(yán)格的來說,這并不是一個CSV文件了,因?yàn)樗臄?shù)據(jù)并不是通過逗號分隔的。在這種情況下,我們可以通過指定分隔符的方式來讀取這個文件,像這樣:
# file_operation.py df3=pd.read_csv("data/test2.csv", sep="|") print("df3:\n{}\n".format(df3))
實(shí)際上,read_csv支持非常多的參數(shù)用來調(diào)整讀取的參數(shù),如下表所示:
詳細(xì)的read_csv函數(shù)說明請參見這里:pandas.read_csv(http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html?spm=a2c4e.11153940.blogcont596296.22.67e04526nmEaeg&highlight=read_csv#pandas.read_csv)
現(xiàn)實(shí)世界并非完美,我們讀取到的數(shù)據(jù)常常會帶有一些無效值。如果沒有處理好這些無效值,將對程序造成很大的干擾。
對待無效值,主要有兩種處理方法:直接忽略這些無效值;或者將無效值替換成有效值。
下面我先創(chuàng)建一個包含無效值的數(shù)據(jù)結(jié)構(gòu)。然后通過pandas.isna函數(shù)來確認(rèn)哪些值是無效的:
# process_na.py import pandas as pd import numpy as np df=pd.DataFrame([[1.0, np.nan, 3.0, 4.0], [5.0, np.nan, np.nan, 8.0], [9.0, np.nan, np.nan, 12.0], [13.0, np.nan, 15.0, 16.0]]) print("df:\n{}\n".format(df)); print("df:\n{}\n".format(pd.isna(df)));****
這段代碼輸出如下:
df: 0 1 2 3 0 1.0 NaN 3.0 4.0 1 5.0 NaN NaN 8.0 2 9.0 NaN NaN 12.0 3 13.0 NaN 15.0 16.0 df: 0 1 2 3 0 False True False False 1 False True True False 2 False True True False 3 False True False False
忽略無效值
我們可以通過pandas.DataFrame.dropna函數(shù)拋棄無效值:
# process_na.py print("df.dropna():\n{}\n".format(df.dropna()));
注:dropna默認(rèn)不會改變原先的數(shù)據(jù)結(jié)構(gòu),而是返回了一個新的數(shù)據(jù)結(jié)構(gòu)。如果想要直接更改數(shù)據(jù)本身,可以在調(diào)用這個函數(shù)的時候傳遞參數(shù) inplace=True。
對于原先的結(jié)構(gòu),當(dāng)無效值全部被拋棄之后,將不再是一個有效的DataFrame,因此這行代碼輸出如下:
df.dropna(): Empty DataFrame Columns: [0, 1, 2, 3] Index: []
我們也可以選擇拋棄整列都是無效值的那一列:
# process_na.py print("df.dropna(axis=1, how='all'):\n{}\n".format(df.dropna(axis=1, how='all')));
注:axis=1表示列的軸。how可以取值'any'或者'all',默認(rèn)是前者。
這行代碼輸出如下:
df.dropna(axis=1, how='all'): 0 2 3 0 1.0 3.0 4.0 1 5.0 NaN 8.0 2 9.0 NaN 12.0 3 13.0 15.0 16.0
替換無效值
我們也可以通過fillna函數(shù)將無效值替換成為有效值。像這樣:
# process_na.py print("df.fillna(1):\n{}\n".format(df.fillna(1)));
這段代碼輸出如下:
df.fillna(1): 0 1 2 3 0 1.0 1.0 3.0 4.0 1 5.0 1.0 1.0 8.0 2 9.0 1.0 1.0 12.0 3 13.0 1.0 15.0 16.0
將無效值全部替換成同樣的數(shù)據(jù)可能意義不大,因此我們可以指定不同的數(shù)據(jù)來進(jìn)行填充。為了便于操作,在填充之前,我們可以先通過rename方法修改行和列的名稱:
# process_na.py df.rename(index={0: 'index1', 1: 'index2', 2: 'index3', 3: 'index4'}, columns={0: 'col1', 1: 'col2', 2: 'col3', 3: 'col4'}, inplace=True); df.fillna(value={'col2': 2}, inplace=True) df.fillna(value={'col3': 7}, inplace=True) print("df:\n{}\n".format(df));
這段代碼輸出如下:
df: col1 col2 col3 col4 index1 1.0 2.0 3.0 4.0 index2 5.0 2.0 7.0 8.0 index3 9.0 2.0 7.0 12.0 index4 13.0 2.0 15.0 16.0
數(shù)據(jù)中常常牽涉到字符串的處理,接下來我們就看看pandas對于字符串操作。
Series的str字段包含了一系列的函數(shù)用來處理字符串。并且,這些函數(shù)會自動處理無效值。
下面是一些實(shí)例,在第一組數(shù)據(jù)中,我們故意設(shè)置了一些包含空格字符串:
# process_string.py import pandas as pd s1=pd.Series([' 1', '2 ', ' 3 ', '4', '5']); print("s1.str.rstrip():\n{}\n".format(s1.str.lstrip())) print("s1.str.strip():\n{}\n".format(s1.str.strip())) print("s1.str.isdigit():\n{}\n".format(s1.str.isdigit()))
在這個實(shí)例中我們看到了對于字符串strip的處理以及判斷字符串本身是否是數(shù)字,這段代碼輸出如下:
s1.str.rstrip(): 0 1 1 2 2 3 3 4 4 5 dtype: object s1.str.strip(): 0 1 1 2 2 3 3 4 4 5 dtype: object s1.str.isdigit(): 0 False 1 False 2 False 3 True 4 True dtype: bool
下面是另外一些示例,展示了對于字符串大寫,小寫以及字符串長度的處理:
# process_string.py s2=pd.Series(['Stairway to Heaven', 'Eruption', 'Freebird', 'Comfortably Numb', 'All Along the Watchtower']) print("s2.str.lower():\n{}\n".format(s2.str.lower())) print("s2.str.upper():\n{}\n".format(s2.str.upper())) print("s2.str.len():\n{}\n".format(s2.str.len()))
該段代碼輸出如下:
s2.str.lower(): 0 stairway to heaven 1 eruption 2 freebird 3 comfortably numb 4 all along the watchtower dtype: object s2.str.upper(): 0 STAIRWAY TO HEAVEN 1 ERUPTION 2 FREEBIRD 3 COMFORTABLY NUMB 4 ALL ALONG THE WATCHTOWER dtype: object s2.str.len(): 0 18 1 8 2 8 3 16 4 24 dtype: int64
本文來自阿里云云棲社區(qū),未經(jīng)許可禁止轉(zhuǎn)載。
更多資訊,盡在云棲科技快訊~
來科技快訊看新聞鴨~
快點(diǎn)關(guān)注我認(rèn)識我愛上我啊~~~
讀:任何原始格式的數(shù)據(jù)載入DataFrame后,都可以使用類似DataFrame.to_csv()的方法輸出到相應(yīng)格式的文件或者目標(biāo)系統(tǒng)里。本文將介紹一些常用的數(shù)據(jù)輸出目標(biāo)格式。
作者:李慶輝
來源:華章科技
DataFrame.to_csv方法可以將DataFrame導(dǎo)出為CSV格式的文件,需要傳入一個CSV文件名。
df.to_csv('done.csv')
df.to_csv('data/done.csv') # 可以指定文件目錄路徑
df.to_csv('done.csv', index=False) # 不要索引
另外還可以使用sep參數(shù)指定分隔符,columns傳入一個序列指定列名,編碼用encoding傳入。如果不需要表頭,可以將header設(shè)為False。如果文件較大,可以使用compression進(jìn)行壓縮:
# 創(chuàng)建一個包含out.csv的壓縮文件out.zip
compression_opts=dict(method='zip',
archive_name='out.csv')
df.to_csv('out.zip', index=False,
compression=compression_opts)
將DataFrame導(dǎo)出為Excel格式也很方便,使用DataFrame.to_excel方法即可。要想把DataFrame對象導(dǎo)出,首先要指定一個文件名,這個文件名必須以.xlsx或.xls為擴(kuò)展名,生成的文件標(biāo)簽名也可以用sheet_name指定。
如果要導(dǎo)出多個DataFrame到一個Excel,可以借助ExcelWriter對象來實(shí)現(xiàn)。
# 導(dǎo)出,可以指定文件路徑
df.to_excel('path_to_file.xlsx')
# 指定sheet名,不要索引
df.to_excel('path_to_file.xlsx', sheet_name='Sheet1', index=False)
# 指定索引名,不合并單元格
df.to_excel('path_to_file.xlsx', index_label='label', merge_cells=False)
多個數(shù)據(jù)的導(dǎo)出如下:
# 將多個df分不同sheet導(dǎo)入一個Excel文件中
with pd.ExcelWriter('path_to_file.xlsx') as writer:
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')
使用指定的Excel導(dǎo)出引擎如下:
# 指定操作引擎
df.to_excel('path_to_file.xlsx', sheet_name='Sheet1', engine='xlsxwriter')
# 在'engine'參數(shù)中設(shè)置ExcelWriter使用的引擎
writer=pd.ExcelWriter('path_to_file.xlsx', engine='xlsxwriter')
df.to_excel(writer)
writer.save()
# 設(shè)置系統(tǒng)引擎
from pandas import options # noqa: E402
options.io.excel.xlsx.writer='xlsxwriter'
df.to_excel('path_to_file.xlsx', sheet_name='Sheet1')
DataFrame.to_html會將DataFrame中的數(shù)據(jù)組裝在HTML代碼的table標(biāo)簽中,輸入一個字符串,這部分HTML代碼可以放在網(wǎng)頁中進(jìn)行展示,也可以作為郵件正文。
print(df.to_html())
print(df.to_html(columns=[0])) # 輸出指定列
print(df.to_html(bold_rows=False)) # 表頭不加粗
# 表格指定樣式,支持多個
print(df.to_html(classes=['class1', 'class2']))
將DataFrame中的數(shù)據(jù)保存到數(shù)據(jù)庫的對應(yīng)表中:
# 需要安裝SQLAlchemy庫
from sqlalchemy import create_engine
# 創(chuàng)建數(shù)據(jù)庫對象,SQLite內(nèi)存模式
engine=create_engine('sqlite:///:memory:')
# 取出表名為data的表數(shù)據(jù)
with engine.connect() as conn, conn.begin():
data=pd.read_sql_table('data', conn)
# data
# 將數(shù)據(jù)寫入
data.to_sql('data', engine)
# 大量寫入
data.to_sql('data_chunked', engine, chunksize=1000)
# 使用SQL查詢
pd.read_sql_query('SELECT * FROM data', engine)
Markdown是一種常用的技術(shù)文檔編寫語言,Pandas支持輸出Markdown格式的字符串,如下:
print(cdf.to_markdown())
'''
| | x | y | z |
|:---|----:|----:|----:|
| a | 1 | 2 | 3 |
| b | 4 | 5 | 6 |
| c | 7 | 8 | 9 |
'''
本文介紹了如何將DataFrame對象數(shù)據(jù)進(jìn)行輸出,數(shù)據(jù)經(jīng)輸出、持久化后會成為固定的數(shù)據(jù)資產(chǎn),供我們進(jìn)行歸檔和分析。
關(guān)于作者:李慶輝,數(shù)據(jù)產(chǎn)品專家,某電商公司數(shù)據(jù)產(chǎn)品團(tuán)隊負(fù)責(zé)人,擅長通過數(shù)據(jù)治理、數(shù)據(jù)分析、數(shù)據(jù)化運(yùn)營提升公司的數(shù)據(jù)應(yīng)用水平。精通Python數(shù)據(jù)科學(xué)及Python Web開發(fā),曾獨(dú)立開發(fā)公司的自動化數(shù)據(jù)分析平臺,參與教育部“1+X”數(shù)據(jù)分析(Python)職業(yè)技能等級標(biāo)準(zhǔn)評審。中國人工智能學(xué)會會員,企業(yè)數(shù)字化、數(shù)據(jù)產(chǎn)品和數(shù)據(jù)分析講師,在個人網(wǎng)站“蓋若”上編寫的技術(shù)和產(chǎn)品教程廣受歡迎。
本書摘編自《深入淺出Pandas:利用Python進(jìn)行數(shù)據(jù)處理與分析》,機(jī)械工業(yè)出版社華章公司2021年出版。轉(zhuǎn)載請與我們?nèi)〉檬跈?quán)。
延伸閱讀《深入淺出Pandas》
推薦語:這是一本全面覆蓋了Pandas使用者的普遍需求和痛點(diǎn)的著作,基于實(shí)用、易學(xué)的原則,從功能、使用、原理等多個維度對Pandas做了全方位的詳細(xì)講解,既是初學(xué)者系統(tǒng)學(xué)習(xí)Pandas難得的入門書,又是有經(jīng)驗(yàn)的Python工程師案頭必不可少的查詢手冊。《利用Python進(jìn)行數(shù)據(jù)分析》學(xué)習(xí)伴侶,用好Python必備。
*請認(rèn)真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。