天天看點

c++讀取utf8檔案_pandas資料讀取

今天呢就給大家分享一個資料分析裡面的基礎内容之pandas資料讀取

資料讀取是進行資料預處理,模組化與分析的前提,不同的資料源,需要使用不同的函數讀取,pandas内置了10餘種資料源讀取函數和對應的資料寫入函數,常見的資料源有3種,分别是資料庫資料,文本檔案(包含一般文本檔案和CSV檔案)和Excel檔案,掌握這三種資料源讀取方法,便能夠完成80%左右的資料讀取工作。下面我們具體瞅瞅;

讀/寫資料庫資料

在生産環境中,絕大多數的資料都存儲在資料庫中,pandas提供了讀取與存儲關系型資料庫資料的函數和方法,除pandas庫外,還需要使用SQLAlchemy庫建立對應的資料庫連接配接,SQLAlchemy配合相應資料庫的python連接配接工具(如,mysql資料庫需要安裝mysqlclient或者pymysql庫,Oracle資料庫需要安裝cx_oracle庫),使用create_engine函數建立一個資料庫連接配接,pandas支援mysql,postgtrsql,Oracle,Sql server和SQLite等主流資料庫,下面将以mysql資料庫為例,介紹pandas資料庫資料得到讀取與存儲。

資料庫資料讀取

pandas實作資料庫資料讀取有三個函數,read_sql,read_sql_table和read_sql_query,read_sql_table隻能讀取資料庫的某一個表格,不能實作查詢的操作,read_sql_query則隻能實作查詢操作,不能直接讀取資料庫中的某個表,read_sql是倆者的結合,既能夠讀取資料庫中的某一個表,也能夠實作查詢操作。

三個函數的文法如下

#導入相關的包from sqlalchemy import create_engineimport pandas as pd​pd.read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None)pd.read_sql_query(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None)pd.read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None)
           

SQLAlchemy連接配接資料庫的代碼如下:

from sqlalchemy import create_engine#建立一個mysql連接配接器,使用者名為root,密碼為1234#位址為127.0.0.1.資料庫名稱為testdb,編碼為utf-8#注意實驗時請填寫自己的資料庫資訊engine = create_engine('mysql+pymysql://root:[email protected]:3306/testdb?charset=utf8')print(engine)
           

在create_engine中輸入的是一個連接配接字元串,在使用python的sqlAlchemy時,mysql和oracle資料庫連接配接字元串的格式如下:

資料庫産品名+連接配接工具名://使用者名:密碼@資料庫ip位址:資料庫端口号/資料庫名稱?charset=資料庫資料編碼

使用read_sql_table,read_sql_query,read_sql函數讀取資料庫資料;

from sqlalchemy import create_engineimport pandas as pd​engine = create_engine('mysql+pymysql://root:Huawei12#[email protected]:3306/example?charset=utf8')print(engine)#列印結果如下#Engine(mysql+pymysql://root:***@192.168.1.45:3306/example?charset=utf8)#使用read_sql_query檢視example中的資料表數目formlist = pd.read_sql_query('show tables',con=engine)print('example資料庫中的表清單為:',formlist)
           
c++讀取utf8檔案_pandas資料讀取
#使用read_sql_table讀取訂單詳情表datail1 = pd.read_sql_table('meal_order_detail1',con=engine)print('使用read_sql_table讀取訂單表的長度為:',len(datail1))
           
c++讀取utf8檔案_pandas資料讀取
c++讀取utf8檔案_pandas資料讀取
#使用read_sql讀取訂單詳情表detail2 = pd.read_sql('select * from meal_order_detail2',con=engine)print('使用read_sql函數+SQL語句讀取的訂單詳情表長度為:',len(detail2))detail3 = pd.read_sql('meal_order_detail3',con=engine)print('使用read_sql函數+表格名稱讀取的訂單詳情表的長度為:',len(detail3))
           
c++讀取utf8檔案_pandas資料讀取

資料庫資料存儲

将DataFrame寫入資料庫中,同樣也要依賴SQLALchemy庫的create_engine函數建立資料庫連接配接,資料庫資料讀取有3個函數,但資料存儲則隻有一個to_sql方法,用例如下:

df.to_sql(name,con,schema=None,if_exists='fail',index=True,index_label=None,dtype=None)使用to_sql方法寫入資料#使用to_sql存儲orderDatadatail1.to_sql('test1',con=engine,index=False,if_exists='replace')#使用read_sql讀取test表formlist1 = pd.read_sql_query('show tables',con=engine)print('新增一個表格後,example資料庫表清單為:',formlist1)
           
c++讀取utf8檔案_pandas資料讀取

讀寫文本檔案

文本檔案是一種由若幹行字元構成的計算機檔案,他是一種典型的順序檔案,CSV是一種用分隔符分割的檔案格式,因為其分隔符不一定是逗号,是以又稱為字元分隔檔案,檔案以純文字形式存儲表格資料,他是一種通用,相對簡單的檔案格式,最廣泛的應用是在程式之間轉義表格資料,而這些程式本身是在不相容的格式上進行操作的,因為大量程式都支援CSV或者其變體,是以可以作為大多數程式的輸入和輸出格式。

文本檔案讀取

pandas提供了read_table來讀取文本檔案,提供了read_csv函數來讀取CSV檔案,二者文法如下:

c++讀取utf8檔案_pandas資料讀取

使用read_table和read_csv函數讀取菜品訂單資訊表

#使用read_table讀取菜品訂單資訊表# order = pd.read_table('../Python資料分析與應用/第4章/任務程式/data/meal_order_info.csv',sep=',',encoding='gbk')# len(order)
           
c++讀取utf8檔案_pandas資料讀取

在讀取過程中,有時候你會遇到這種報錯,莫得荒,我也不知道為啥,但是我們可以通過讀取檔案的方式讀取文本,如下:

f=open('../meal_order_info.csv')order=pd.read_table(f,sep=',',encoding='utf-8')len(order)​order1 = pd.read_csv('../meal_order_info.csv',encoding='utf-8',engine='python')len(order1)
           

更改參數讀取表的訂單資訊

f=open('../meal_order_info.csv')order2=pd.read_table(f,sep=';',encoding='utf-8')​order3 = pd.read_csv('../meal_order_info.csv',encoding='gbk',header=None,engine='python')len(order3)
           

文本檔案存儲

文本檔案的存儲和讀取類似,對于結構化資料,可以通過pandas中的to_csv函數實作,常用參數與文法如下:

to_csv(path_or_buf=None, sep=',', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression=None, quoting=None, quotechar='"', line_terminator='', chunksize=None, tupleize_cols=None, date_format=None, doublequote=True, escapechar=None, decimal='.')
           

使用to_csv函數将資料寫入CSV檔案中

#将order以csv格式存儲order.to_csv('../tmp/orderInfo.csv',sep=';',index=False)os.listdir('../tmp')
           
c++讀取utf8檔案_pandas資料讀取

讀寫Excel檔案

Excel是微軟公司的辦公軟體Microsoft office的元件之一,他可以對資料進行處理,統計分析等操作,廣泛的應用與管理,财經和金融等衆多領域。

Excel檔案讀取

pandas提供了read_excel函數來讀取"xls","xlsx"倆種excel檔案,其文法如下:pd.read_excel(io, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=True, **kwds)
           

使用read_excel函數讀取菜品訂單資訊表

user = pd.read_excel('../users.xlsx')len(user)user
           
c++讀取utf8檔案_pandas資料讀取

Excel檔案存儲

将檔案存儲為Excel檔案,可以使用to_excel函數,其文法格式如下:

to_excel(excel_writer, sheet_name='Sheet1', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, encoding=None, inf_rep='inf', verbose=True, freeze_panes=None)
           

使用to_execl函數将資料存儲為Excel檔案

user.to_excel('../tmp/userInfo.xlsx',sheet_name='Sheet3')os.listdir('../tmp')
           

嗯,這就是我們常用到的pandas讀取檔案的一些操作,貌似沒什麼難的,孰能生巧就可,下篇文章為大家分享pandas的常用操作,祝大家一臂之力登上資料分析的神壇。

哦,對啦,該篇文章的素材直接來源為網絡《python資料分析》