【问题标题】:When iterating through CSV file and printing the rows, only the first row gets printed遍历 CSV 文件并打印行时,仅打印第一行
【发布时间】:2017-04-24 06:44:31
【问题描述】:

我已经使用 Pandas 加载了一个 CSV 文件。 CSV 文件有 4000 行。 它正确加载。打印出数据框时,将打印所有 4000 行。 但是当我使用“for”循环遍历行时,它只打印文件中的第一行。

这是我的代码:

import pandas as pd

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

一个想法? 谢谢!

【问题讨论】:

标签: python csv pandas


【解决方案1】:

在您的情况下,我认为以下示例提供了解决方案,并且 提供执行时间。对于这个数量的行,我将使用 itertuples()

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()]

【讨论】:

  • 感谢您的详细解答!
【解决方案2】:

使用 iterrows() 循环遍历每一行。默认迭代只会显示列。

for sample in df.iterrows():
    print sample

【讨论】:

  • 感谢您的回答!
【解决方案3】:

要迭代 DataFrame 行,您可以使用 .iterrows() 函数。

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

【讨论】:

    猜你喜欢
    • 2018-08-04
    • 1970-01-01
    • 2012-03-26
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    相关资源
    最近更新 更多