(一)读取csv文件
使用函数:read_cdv(),具体详见:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
1.本地读取,实例1:
>>> import pandas as pd
>>> df=pd.read_csv('F:\\python_test\\binary.csv')
>>> df
Int64Index: 400 entries, 0 to 399
Data columns (total 4 columns):
admit 400 non-null values
gre 400 non-null values
gpa 400 non-null values
rank 400 non-null values
dtypes: float64(1), int64(3)
实例2:
import csv
csvfile = file('F:\\python_test\\csv_test.csv', 'rb')
reader = csv.reader(csvfile)
for line in reader:
print line
csvfile.close()
2.网络读取
import pandas as pd
data_url = "https://****.csv" #填写url读取
df = pd.read_csv(data_url)
3.数据写入import csv
csvfile = file('F:\\python_test\\csv_test.csv', 'wb')
writer = csv.writer(csvfile)
writer.writerow(['姓名', '年龄', '电话'])
data = [
('小河', '25', '12345'),
('小芳', '19', '78945')
]
writer.writerows(data)
csvfile.close()
(二)读取mysql数据
Mysql基本教程:http://www.runoob.com/mysql/mysql-tutorial.html
假设数据库安装在本地,用户名为username,密码为password,要读取mydb数据库中的数据
import pandas as pd
import MySQLdb
mysql= MySQLdb.connect(host='localhost', port=3306,user='username', passwd='password', db='mydb')
df = pd.read_sql('select * from test;', con=mysql)
mysql.close()
(三)读取excel1导入模块
import xlrd
2 打开excel文件
data = xlrd.open_workbook('1.xlsx')
3 获取一个工作表方法
table = data.sheets()[0] #通过索引顺序获取
table = data.sheet_by_index(0) #通过索引顺序获取
table = data.sheet_by_name(u'Sheet1')#通过名称获取
4 获取整行或整列的值,-->返回数组
table.row_values(i)
table.col_values(i)
5 获取行数和列数
nrows = table.nrows
ncols = table.ncols
6 循环表获取行数据,--->返回数据
for i in range(nrows ):
print table.row_values(i)
7 单元格
cell_A1 = table.cell(0,0).value
cell_C4 = table.cell(2,3).value
也可以使用行列号进行索引
cell_A1 = table.row(0)[0].value
cell_A2 = table.col(1)[0].value
参考:http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html