0

I am trying to write code to load an excel file that will return:

  1. the entire data frame
  2. total number of rows
  3. total number of columns

I wrote the following code but it gave an error: TypeError: cannot unpack non-iterable int object Can you please help me with this, thank you!

def load_data():

    import pandas as pd  
    df = pd.read_csv("myfile.csv") 
    num_rows = df.shape[0]  
    num_cols = df.shape[1]

    return num_rows
    return num_cols
df, num_rows, num_cols = load_data()
1
  • There is no point in having two return statements like that. The second one will never run. What IDE are you using, that wouldn't point that out? Don't put your import inside the function. Also, is there any point in making this a function in the first place? Commented Nov 24, 2019 at 20:20

3 Answers 3

1

Try this!

import pandas as pd   

def load_data():

    df = pd.read_csv("myfile.csv") 
    num_rows = df.shape[0]  
    num_cols = df.shape[1]

    return df, num_rows, num_cols

df, num_rows, num_cols = load_data()

you have to return your variables all at once. Best of luck!

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

Comments

1

You return it wrong. You need to return a tuple as follows

def load_data():

    import pandas as pd  
    df = pd.read_csv("myfile.csv") 
    num_rows = df.shape[0]  
    num_cols = df.shape[1]

    return df, num_rows, num_cols

df, num_rows, num_cols = load_data()

Comments

0

A few things:

  • The second return statement will never be run.
  • Don't put import statements inside a function.
  • I don't see much of a reason to even use a function for this.
  • That isn't an excel file, it's just CSV.
import pandas as pd

df = pd.read_csv('myfile.csv')
num_rows, num_cols = df.shape

Let me know if you have any questions :)

Comments

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.