簡體   English   中英

在python中按列讀取csv的問題

[英]problems reading a csv by column in python

我有一個CSV文件,其中包含空格,即空行或隨機新行,如下例所示

header1,data1
header2,data2

header4,data4

header6,data6

當CSV沒有空格時,下面的示例工作正常,但有沒有辦法按空格加載CSV?

import csv

file = csv.reader(open('file.csv'))
blob = zip(*file)

熊貓會工作:

import pandas
pandas.read_csv("tmp.txt", header=None)

         0      1
0  header1  data1
1  header2  data2
2      NaN    NaN
3  header4  data4
4      NaN    NaN
5  header6  data6

你可能想要過濾出NaN。

我會在zip [python 2假設為open ]之前過濾行:

>>> import csv
>>> with open("blank.csv", "rb") as fp:
...     reader = csv.reader(fp)
...     rows = [line for line in reader if line]
...     blob = zip(*rows)
...     
>>> blob
[('header1', 'header2', 'header4', 'header6'), ('data1', 'data2', 'data4', 'data6')]

if line此處的if line基本等於if len(line) > 0

暫無
暫無

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

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