如何在Python中阅读特定的列和行?

时间:2017-03-21 07:30:43

标签: python csv

  

时间戳SP DP
  20-03-2017 10:00:01 50 60.5
  20-03-2017 10:10:00 60 70
  20-03-2017 10:40:01 75 80
  20-03-2017 11:05:00 44 65
  20-03-2017 11:25:01 98 42
  20-03-2017 11:50:01 12 99
  20-03-2017 12:00:05 13 54
  20-03-2017 12:05:01 78 78
  20-03-2017 12:59:01 15 89
  20-03-2017 13:00:00 46 99
  20-03-2017 13:23:01 44 45
  20-03-2017 13:45:08 80 39

import csv    

output = []

f = open( 'test.csv', 'r' ) #open the file in read universal mode
for line in f:
    cells = line.split( "," )
    output.append( ( cells[ 0 ], cells[ 1 ] ) ) #since we want the first, second column
print (output)

如何阅读特定列和特定行?

期望的输出:

我只想要第一列和第二行;

  

时间戳SP
  20-03-2017 10:00:01 50
  20-03-2017 10:10:00 60

怎么做?

3 个答案:

答案 0 :(得分:3)

使用您的csv模块,并计算行数(使用enumerate() function或使用itertools.islice()来限制读取的数量:

import csv

output = []

with open( 'test.csv', 'r', newline='') as f:
    reader = csv.reader(f)
    for counter, row in enumerate(reader):
        if counter > 2:
            # read only the header and first two rows
            break
        output.append(row[:2])

或使用islice()

import csv
from itertools import islice

with open( 'test.csv', 'r', newline='') as f:
    reader = csv.reader(f)
    output = list(islice((row[:2] for row in reader), 3))

答案 1 :(得分:2)

您可以使用索引切片。只需从源代码中读取csv。

from pandas import *

df = read_csv("Name of csv file.")

df2 = df.ix[:1, 0:2]

print df2

试试吧。

答案 2 :(得分:1)

您可以使用pandas来阅读它。

import pandas
df = pandas.read_csv("filepath", index_col = 0)

然后你可以通过

调用第一列和第二行
df.SP.head(2)

df.ix[:1, 0:2] # first row and column first two column