簡體   English   中英

如何使用python從csv導入數據

[英]How to import data from csv using python

我是python的新手。
我在尋找一種將csv文件中的數據導入到我的python代碼中的方法時遇到很多困難。
我的csv文件不是逗號分隔的數據。
我正在使用Python 2.7。

可以說您的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']這樣簡單地獲取它,依此類推

這是熊貓絕對不可思議的事情之一。 我強烈建議安裝和使用熊貓,而不只是csv模塊。

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

然后,您只需輸入以下內容即可查看新數據框的詳細信息

df.info()

上面,您提到要查看第三行的第四列。 使用數據框,您可以通過輸入

df[3]['Column 4']

了解有關您要導入哪些數據以及原因的更多信息,這將非常有幫助。

要將一個小的文本文件放入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類型,我也強烈建議您研究熊貓

對我來說,它的CSV導入以及隨后的修改和分析功能比標准的python產品要容易得多,功能也更強大。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM