如何使用python从csv导入数据

时间:2015-03-13 07:10:31

标签: python python-2.7 csv import

我是python的新手 我在寻找一种将数据从csv文件导入我的python代码时遇到了很多困难 我的csv文件不是逗号分隔的数据 我使用的是Python 2.7。

3 个答案:

答案 0 :(得分:1)

让我们说你的people.csv文件是:

id,name,age,height,weight
1,Alice,20,62,120.6
2,Freddie,21,74,190.6
3,Bob,17,68,120.0

以下代码将返回字典。

import csv
input_file = csv.DictReader(open("people.csv"))
for row in input_file:
    print row

输出:

{'age': '20', 'height': '62', 'id': '1', 'weight': '120.6', 'name': 'Alice'}
{'age': '21', 'height': '74', 'id': '2', 'weight': '190.6', 'name': 'Freddie'}
{'age': '17', 'height': '68', 'id': '3', 'weight': '120.0', 'name': 'Bob'}

这是非常有效的方式,因为csv在字典中表示。 让我们说,您希望从第一行获取详细信息,然后您可以简单地将其设置为row['age']等等

答案 1 :(得分:1)

这是熊猫绝对精彩的事情之一。我强烈建议安装和使用pandas而不仅仅是csv模块。

import pandas as pd
df = pd.read_csv(filename)

然后,您只需输入

即可查看新数据框的详细信息
df.info()

上面,您提到要查看第3行的第4列。使用数据框,您可以通过键入

来获得
df[3]['Column 4']

答案 2 :(得分:0)

获得更多关于您要导入哪些数据及其原因的信息真的很有帮助!

要将一个小文本文件放到python中,然后在其中阅读一下,这就是我要做的事情:

current_csv = csv_list[somecounter]  
#this is assuming you have a whole directory of files 
#and you implemt some file picking beforehand

infile= open(current_csv, 'r')
import csv
table = [] #initialize a table

#initialize a counter for the rows
rows=0

#read the first 50 lines of the csv into table
#depending on your file, you should probably implement some logic to see how many rows you need
for row in csv.reader(infile):
     rows+=1
     if rows<50:
         table.append(row)
infile.close()

使用该表,您现在可以执行以下操作(假设您拥有固定的CSV结构)Filename = table[0]或通过循环遍历表来搜索内容。

根据您的CSV类型,我强烈建议您查看pandas

对我而言,它的CSV导入和后续修改和分析功能比标准的蟒蛇产品更容易,更强大。