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‘)