[英]When iterating through CSV file and printing the rows, only the first row gets printed
我已經使用熊貓加載了CSV文件。 CSV文件具有4000行。 它已正確加載。 打印出數據框時,將打印所有4000行。 但是,當我使用“ for”循環遍歷各行時,它僅打印文件中的第一行。
這是我的代碼:
import pandas as pd
df = pd.read_csv('EX2_EM_GMM.csv')
for sample in df:
print sample
有想法嗎? 謝謝!
要遍歷DataFrame
行,可以使用.iterrows()函數。
for index, row in df.iterrows():
# Process each row
在您的情況下,我認為以下示例提供了解決方案,還提供了執行時間。 對於此行數,我將使用itertuples()
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()]
使用iterrows()遍歷每一行。 默認迭代將僅顯示列。
for sample in df.iterrows():
print sample
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.