1

I need to write the program that loops through the columns of data. Resetting the variable based on the cell value and each column representing a variable.

The variables in the exercise are dependent on these values that are being looped through.

How can I loop through the rows with each iteration of the loop increasing the value by 1?

df=pd.DataFrame(r'C:/Users/user.name/Desktop/P_list.xlsx',sheet_name = 'Sheet1')
for i in range(0,5000):

    df2 = pd.read_excel(r'C:/Users/user.name/Desktop/P_list.xlsx',sheet_name = 'Sheet1'), index = list(range(i,5000,1), columns=list(range(0)))
    df3 = pd.read_excel(r'C:/Users/user.name/Desktop/P_list.xlsx',sheet_name = 'Sheet1'), index = list(range(i,5000,1), columns=list(range(1)))
    df4 = pd.read_excel(r'C:/Users/user.name/Desktop/P_list.xlsx',sheet_name = 'Sheet1'), index = list(range(i,5000,1), columns=list(range(2)))
    df5 = pd.read_excel(r'C:/Users/user.name/Desktop/P_list.xlsx',sheet_name = 'Sheet1'), index = list(range(i,5000,1), columns=list(range(3)))
    firstname = df2
    lastname = df3
    address = df4
    number= df5

#performed exercise

2
  • 1
    Idea is not cleat to me. What do you mean by saying program needs to loop through the sheets of column's data? Commented Nov 18, 2019 at 16:40
  • It needs to loop through the columns of data. Resetting the variable based on the cell value. Each column representing a variable. Commented Nov 18, 2019 at 16:42

1 Answer 1

5

I have tried this on Jupyter. This is needed to load the Excel to df:

import numpy as np
import pandas as pd
import xlrd
df = pd.read_excel('Sample.xlsx', sheet_name = 0)

Then looping towards the column names is like this:

for col in df.columns:
    print(col)

And looping towards the data is this:

for col in df.columns:
    print("NEW ROW ----------")
    for val in df[col]:
        print (val)

This is the printed data:

enter image description here

Another way to do it is to loop through the columns and the rows:

columns = len(df.columns)
rows = len(df)

for column in range(columns):
    print("-----------")
    for row in range(rows):
        print(df.loc[row][column])

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

This got me on track, I was able to apply this and manipulate it to fit what I was working on! Thank you!
@SublimizeD - welcome :) I am also studying pandas and numpy now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.