简体   繁体   English

遍历CSV文件并打印行时,仅打印第一行

[英]When iterating through CSV file and printing the rows, only the first row gets printed

I've loaded a CSV file using Pandas. 我已经使用熊猫加载了CSV文件。 The CSV file has 4000 rows. CSV文件具有4000行。 It loaded correctly. 它已正确加载。 When printing out the data frame, all 4000 rows are printed. 打印出数据框时,将打印所有4000行。 But when I iterate through the rows using a "for" loop, it only prints the first row in the file. 但是,当我使用“ for”循环遍历各行时,它仅打印文件中的第一行。

This is my code: 这是我的代码:

import pandas as pd

df = pd.read_csv('EX2_EM_GMM.csv')
for sample in df:
    print sample

An Ideas? 有想法吗? Thanks! 谢谢!

For iterating over DataFrame rows you can use .iterrows() function. 要遍历DataFrame行,可以使用.iterrows()函数。

for index, row in df.iterrows():
    # Process each row

In your case I think following examples provide solution and also providing time of execution. 在您的情况下,我认为以下示例提供了解决方案,还提供了执行时间。 for this amount of rows I will use itertuples() 对于此行数,我将使用itertuples()

itertuples() and iterrows() itertuples()iterrows()

import pandas as pd
import numpy as np

di = {k:np.random.randn(4000) for k in ["a", "b", "c", "d"]}
df = pd.DataFrame(di)

for row in df.itertuples():
    print row

%timeit [row for row in df.itertuples()]

%timeit [row for row in df.iterrows()]

输出样本 执行时间的结果

Use iterrows() to loop through each of the rows. 使用iterrows()遍历每一行。 The default iteration will just show the columns. 默认迭代将仅显示列。

for sample in df.iterrows():
    print sample

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

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