0

This question may have been asked for fundamentals of Python, unfortunately, I spent an hour looking for the answer, but couldn't find it. So I am hoping for someone's input. I am used to writing Class where I can give self and get the variable into the def function from another function. How do I capture that variable without writing a Class function? Is there a way? Thanks!

import pandas as pd 

file_Name = 'test.xlsx'

def read_file():
    df = pd.read_excel(file_Name)
    return df
read_file() 

def clean_data():
    text_data = df['some_column_name'].str.replace(';',',') # How to get df from read_file() function?
    return text_data
clean_data()
4
  • You don't need arguments here. Just call it in your clean_data method. (e.g df = read_file() ) Commented Jul 23, 2018 at 18:10
  • To pass variables to a function's scope, use the function's arguments Commented Jul 23, 2018 at 18:11
  • Do you mean something like this?: read_file(x), where x is variable to be captured. Commented Jul 23, 2018 at 18:12
  • @sharp see my answer Commented Jul 23, 2018 at 18:16

3 Answers 3

1

You're overthinking it:

df = read_file()
clean_data()  # Uses the global variable df capturing the return value of read_file

Or course, clean_data should take an argument rather than using a global variable.

def clean_data(f):
    text_data = f['some_column_name'].str.replace(';', ',')
    return text_data

f = read_file()
clean_data(f)
Sign up to request clarification or add additional context in comments.

Comments

1

Call the first function and save the returned dataframe in a variable df. Then call the second function (clean_data) and pass this df inside it as argument.

Use this:

import pandas as pd 

file_Name = 'test.xlsx'
import pandas as pd 

def read_file():
    df = pd.read_excel(file_Name)
    return df
df = read_file() 

def clean_data(df):
    text_data = df['some_column_name'].str.replace(';', ',')
    return text_data

clean_data()

Comments

0

In general... you can use global variables. But with how your method is set up, you should just do

df = read_file()

inside of your clean_data() method. Then use df from there. Notice df is just the local name for the result of calling read_file(), you can call it anything.

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.