Mr.Riply
Mr.Riply

Reputation: 845

iterate thrugh values in each columns

How to iterate through data in a DataFrame, I would like to iterate through all the data in the first column, before moving to the next.

with the code below I get to iterate over the data row by row for all columns

enter image description here

Instead, I would like to iterate through all the data in the first column before moving to the next.

enter image description here

import time
import pandas as pd


df = pd.read_csv('testDATA.csv')

for i, row in df.iterrows():
    #print(row)
    time.sleep(1)
    for j, column in row.iteritems():
        print(column)
        time.sleep(1)

print(df)

Upvotes: 3

Views: 136

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

pandas.DataFrame itself has DataFrame.iteritems() method to iterate over all the columns of a dataframe:

In [8]: df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})                                                 

In [9]: for col_name, col_data in df.iteritems(): 
   ...:     print(col_name) 
   ...:     print(col_data.values)   # can be iterated separately 
   ...:                                                                                                     
col1
[1 2]
col2
[3 4]

Upvotes: 2

BrockMarekins
BrockMarekins

Reputation: 76

Try to rotate the logic. First of all iterate through the items and then again by its items. Examine the following code:

for i, column in df.iteritems():
    for j, row in column.iteritems():
        print(row)

Upvotes: 2

ansev
ansev

Reputation: 30920

Use DataFrame.transpose an then use your code...

import time
import pandas as pd
df = pd.read_csv('testDATA.csv')

df=df.T

for i, row in df.iterrows():
    #print(row)
    time.sleep(1)
    for j, column in row.iteritems():
        print(column)
        time.sleep(1)

print(df)

Upvotes: 2

Related Questions