Rock1432
Rock1432

Reputation: 209

Iterate over nth row of a dataframe

I have a csv file which is a single column of data. I need to split this into three separate columns through iterating through every third term. E.g.

My single column is currently of the format:

A
B
C
A
B
C
A
B
C

I need three columns containing A, B, and C. My plan was to iterate through the single column three times and cast this to 3 lists. How do I go about iterating every third term to do so? E.g. how do I incorporate [::3] into the for loop below?

import pandas as pd

df = pd.read_csv('Names+grades.txt')
initial = []
name = []
job=[]

for index, row in df.iterrows():
    initial.append(row['Raw data'])

Thanks for any help that you can provide.

Upvotes: 2

Views: 1620

Answers (2)

Umar.H
Umar.H

Reputation: 23099

you can split each dataframe with integer slicing and just re-concat each part.

df_new = pd.concat([df.iloc[::3].reset_index(drop=True)
           ,df.iloc[1::3].reset_index(drop=True)
           ,df.iloc[2::3].reset_index(drop=True)],axis=1)


df_new.columns = ['A','B','C']

print(df_new)

   A  B  C
0  A  B  C
1  A  B  C
2  A  B  C

Upvotes: 0

mcskinner
mcskinner

Reputation: 2748

df = pd.read_csv('Names+grades.txt')
pd.DataFrame({'A': df[::3], 'B': df[1::3], 'C': df[2::3]}) 

Upvotes: 2

Related Questions