Python 外部數據的讀寫(cvs,excel)
阿新 • • 發佈:2018-01-30
文件 pytho 實踐 ticket data 讀取excel sep taf tutorial
python 外部數據的讀寫
來自紀路,Python數據科學實踐指南
CSV
- CSV是什麽?
逗號分隔值(Comma-Separated Values,CSV,有時也稱為字符分隔值,因為分隔字符也可以不是逗號) - csv文件讀取(str)
import csv with open("D:/課件/《python數據科學》/data_science_tool_book_code/chapter7/test.csv") as fr: rows = csv.reader(fr) for row in rows: #這裏要縮進,rows相當於一個流,必須在文件開啟時使用 print(row) ###################### [‘PassengerId‘, ‘Pclass‘, ‘Name‘, ‘Sex‘, ‘Age‘, ‘SibSp‘, ‘Parch‘, ‘Ticket‘, ‘Fare‘, ‘Cabin‘, ‘Embarked‘] [‘892‘, ‘3‘, ‘Kelly, Mr. James‘, ‘male‘, ‘34.5‘, ‘0‘, ‘0‘, ‘330911‘, ‘7.8292‘, ‘‘, ‘Q‘] [‘893‘, ‘3‘, ‘Wilkes, Mrs. James (Ellen Needs)‘, ‘female‘, ‘47‘, ‘1‘, ‘0‘, ‘363272‘, ‘7‘, ‘‘, ‘S‘] [‘894‘, ‘2‘, ‘Myles, Mr. Thomas Francis‘, ‘male‘, ‘62‘, ‘0‘, ‘0‘, ‘240276‘, ‘9.6875‘, ‘‘, ‘Q‘] [‘895‘, ‘3‘, ‘Wirz, Mr. Albert‘, ‘male‘, ‘27‘, ‘0‘, ‘0‘, ‘315154‘, ‘8.6625‘, ‘‘, ‘S‘] [‘896‘, ‘3‘, ‘Hirvonen, Mrs. Alexander (Helga E Lindqvist)‘, ‘female‘, ‘22‘, ‘1‘, ‘1‘, ‘3101298‘, ‘12.2875‘, ‘‘, ‘S‘] [‘897‘, ‘3‘, ‘Svensson, Mr. Johan Cervin‘, ‘male‘, ‘14‘, ‘0‘, ‘0‘, ‘7538‘, ‘9.225‘, ‘‘, ‘S‘]
- csv文件讀取(字典)
import csv
with open(‘D:/課件/《python數據科學》/data_science_tool_book_code/chapter7/test.csv‘) as fr:
rows=csv.DictReader(fr)
for row in rows:
print(row)
- csv文件寫
import csv with open(‘./csv_tutorial.csv‘,‘a‘) as fw: writer=csv.writer(fw) writer.writerow([‘c1‘,‘c2‘,‘c3‘]) #同樣,必須縮進
EXCEL
- pandas
一個強大的數據處理庫,其中就包括了excel格式的處理 - 讀取excel:
import pandas as pd
from pandas import read_excel
pd.set_option(‘display.max_columns‘,4)
pd.set_option(‘display.max_rows‘,6)
df= read_excel(‘D:/課件/《python數據科學》/data_science_tool_book_code/chapter8/A0202.xls‘,‘Sheet1‘)
print(df)
- 寫excel
import pandas as pd from pandas import DataFrame df=DataFrame([[1,2,3,4],[5,6,7,8],[9,10,11,12]],index=[0,1,2],columns=list("ABCD")) df.to_excel(‘test.xls‘)
Python 外部數據的讀寫(cvs,excel)