Pandas大全(一直补充)2

二、读取 csv 文件

1、普通方法读取

最简单、最直接的就是 open() 打开文件:

with open("./marks.csv") as f:
    for line in f:        print line

2、Python 中还有一个 csv 的标准库,足可见 csv 文件的使用频繁了。

import csv 
csv_reader = csv.reader(open("./marks.csv"))
for row in csv_reader:
    print row
3、 用 Pandas 读取

如果对上面的结果都有点不满意的话,那么看看 Pandas 的效果:

>>> import pandas as pd
>>> marks = pd.read_csv("./marks.csv")
>>> marks
       name  physics  python  math  english
0    Google      100     100    25       12
1  Facebook       45      54    44       88
2   Twitter       54      76    13       91
3     Yahoo       54     452    26      100

看了这样的结果,它就是一个 DataFrame 数据。

还有另外一种方法:

pd.read_table("./marks.csv", sep=",")
       name  physics  python  math  english
0    Google      100     100    25       12
1  Facebook       45      54    44       88
2   Twitter       54      76    13       91
3     Yahoo       54     452    26      100

三、读取其它格式数据

csv 是常用来存储数据的格式之一,此外常用的还有 MS excel 格式的文件,以及 json 和 xml 格式的数据等。它们都可以使用 pandas 来轻易读取。

1、.xls 或者 .xlsx

用pip 安装 openpyxl 模块:sudo pip install openpyxl。继续:

xls = pd.ExcelFile("./marks.xlsx")
>>> xls = pd.ExcelFile("./marks.xlsx")
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet1 = xls.parse("Sheet1")
>>> sheet1
   0    1    2   3    4
0  5  100  100  25   12
1  6   45   54  44   88
2  7   54   76  13   91
3  8   54  452  26  100


上一篇:Pandas大全(一直补充)

猜你喜欢

转载自blog.csdn.net/qq_31967985/article/details/79961761
今日推荐