简体   繁体   English

从CSV文件导入行,但不是整行

[英]Importing row from csv file but not the whole row

So I'm importing a row from a .csv file into Python, it's going through ok but it's printing the whole row but I only need the first 15 cells down. 因此,我将.csv文件中的一行导入到Python中,一切正常,但是将打印整行,但是我只需要向下15个单元格。

I'm now trying to break the script with a while statement at column 15 but cannot think of how to word it. 我现在正在尝试在第15列使用while语句来破坏脚本,但无法考虑如何写该词。 Can anyone point me in the right direction with this? 有人可以为此指出正确的方向吗?

So far I have the following code: 到目前为止,我有以下代码:

import csv
f=open ('example')
csv_f=csv.reader(f)

for row in csv_f:
    print(row[8]):
        while condition:
            ...

You could iterate over just the first 15 rows: 您可以仅对前15行进行迭代:

from itertools import islice
for row in islice(csv_f, 15):
    ...
csv_f = csv.reader(f)
for line_number, row in enumerate(csv_f):
    if line_number >= 15:
        break
    print(row[8])

I would suggest you to use pandas in this case, since you probably don't want a DataFrame , here's how you can get a list of list: 我建议您在这种情况下使用pandas ,因为您可能不希望使用DataFrame ,这是获取列表列表的方法:

import pandas as pd
df = pd.read_csv('your_csv.csv', usecols=range(15))
mylol = df.values.tolist()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM