How to create a Python df from a .csv using a defined function

Question:

I’m trying to produce a function to ultimately read in .csv files and create a df.

I’ve written the following code which imports the file and creates the df (df_input) but I can’t reference df_input outside the function.

def combine_files(data_file):
   df_input = pd.read_csv(data_file)
   return df_input

When I action the function with the following code:

combine_files('datasets/202105.csv')

It returns the contents of df_input but if I try to reference df_input outside the function I get the following error:

NameError: name 'df_input' is not defined

Any help would be greatly appreciated. Thank you

Asked By: Andy King

||

Answers:

You need to assign the result from combine_files to a variable.

df = combine_files('datasets/202105.csv')

Then you can use df

Answered By: AndrzejO
def combine_files(data_file):
   df_input = pd.read_csv(data_file)
   return df_input

data = combine_files('datasets/202105.csv')

print(data)
Answered By: Vitaliy Korolyk
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.