I am new to Python and building a function to read CSV. I am trying to use the pandas.read_csv()
inside my function,and while the code gets compiled-i dont see the dataset (I know its an overkill, but am trying to learn it using a trial and error method).
>>> def CSV(filename): dataset=pd.read_csv(filename)
I expect that when i run CSV('abc.csv')
, it should create a df in my variable explorer. Unfortunately, the function gets compiled, but nothing is there
def CSV(filename): dataset=pd.read_csv(filename) CSV('banking.csv')
Advertisement
Answer
The following example, taken from Read the Docs: Variables and Scope, illustrates the issue that you’re experiencing — dataset
was created in your CSV
function, but no longer exists outside of the scope of that function:
# This is a global variable a = 0 if a == 0: # This is still a global variable b = 1 def my_function(c): # this is a local variable d = 3 print(c) print(d) # Now we call the function, passing the value 7 as the first and only parameter my_function(7) # a and b still exist print(a) print(b) # c and d don't exist anymore -- these statements will give us name errors! print(c) print(d)
In this example, variable d
is similar to your dataset
variable — it’s trashed as soon as execution of the function is complete.
Instead:
def CSV(filename): return pd.open_csv(filename) df = CSV('banking.csv')
will create a DataFrame variable df
that you can view in variable explorer.