简体   繁体   English

Python Pandas read_csv 仅从 CSV 文件中读取一行

[英]Python Pandas read_csv reads only single line from CSV file

I am writing a code to read and extract parameters from each row of a CSV file.我正在编写代码以从 CSV 文件的每一行读取和提取参数。

From each row, I get a list of parameter values arranged by datestamps and values.从每一行,我得到一个按日期戳和值排列的参数值列表。 An example csv file is as below:一个示例 csv 文件如下:

Row1: 'Fanspeed','Value=32','Datetime=05-01-2015','Fanspeed','Value=32','Datetime=05-02-2015' 

Row2: 'Fanspeed','Value=32','Datetime=05-03-2015','Fanspeed','Value=32','Datetime=05-04-2015'

If I use the Pandas read_csv to read in the file and then print the output, it only prints the first row.如果我使用 Pandas read_csv读入文件然后打印输出,它只会打印第一行。 However, when I use the csv.reader function, I get the correct output.但是,当我使用csv.reader函数时,我得到了正确的输出。 My program looks like this:我的程序是这样的:

csv_f = pd.read_csv('test.csv')
for row in csv_f: 
    csv_f = pd.read_csv('test.csv') 
    print csv_f

I get only the following output:我只得到以下输出:

'Fanspeed','Value=32','Datetime=05-01-2015','Fanspeed','Value=32','Datetime=05-02-2015'

However, on running the same program with the csv.reader function as below:但是,在使用csv.reader函数运行相同的程序时,如下所示:

f = open('test.csv') 
csv_f = csv.reader(f)
for row in csv_f: 
    csv_f = pd.read_csv('test.csv') 
    print csv_f

I get the correct output.我得到正确的输出。 Could someone help me?有人可以帮助我吗?

First of all , you can try to pass 'header=None' to indicate the first row will be data instead of the headers.首先,您可以尝试传递 'header=None' 以指示第一行将是数据而不是标题。

csv_f = pd.read_csv('test.csv', header=None) 
print csv_f

Secondly, what the read_csc returns is already a DataFrame, so you should directly working on it.其次, read_csc 返回的已经是一个DataFrame,所以你应该直接处理它。 More information pandas.read_csv更多信息pandas.read_csv

Try this:试试这个:

    csv_f = pd.read_csv('test.csv')
    print csv_f.head()
    #for row in csv_f: 
        #csv_f = pd.read_csv('test.csv') 
        #print csv_f

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

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