1

i want to print a column of a dataframe in a function. it says name 'data' is not defined. How do I make it global?

my function is:

def min_function():
    print("Choose action to be performed on the data using the specified metric. Options are list, correlation")
    action = input()
    if action == "list":
        print("Ranked list of countries' happiness scores based the min metric")
        print(data['country'], data.sort_values(['min_value'], ascending=[0,0]))

data is my dataframe.

Jagruthi C
  • 71
  • 7
  • 1
    Nothing in your code references `df`. – chepner Apr 08 '19 at 17:38
  • sorry it's 'data' and not 'df' – Jagruthi C Apr 08 '19 at 17:46
  • Well, you need a global (or at least some other non-local) variable `data` to exist before `min_function` tries to access it. It's impossible to tell from the code you posted if that is true or not. – chepner Apr 08 '19 at 17:49
  • @chepner data is the dataframe that is computed just before the function definition. Later I print 2 columns of the dataframe in the function which throws "NameError: name 'data' is not defined"-- may be because the function thinks of data as a variable? I have no clue – Jagruthi C Apr 08 '19 at 17:55
  • Neither do I, because I only have your word that `data` was properly defined before you called `min_function`. You need to provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – chepner Apr 08 '19 at 18:00

2 Answers2

0

Don't :-)

import it and use it as a parameter for your function. This way you will be able to use other dataframes as well. If there really is, ever will, and ever should be one dataframe of data use the singleton-pattern (https://en.wikipedia.org/wiki/Singleton_pattern) and still import it.

phylogram
  • 123
  • 7
0

While it is true, that you should think hard before introducing global variables, you can do it in two ways:

Either just define the variable in the file you want to access it and then just use it, or you use the global keyword in a function before defining the variable.

Note, that with both approaches, you can only access the variable within your file. If that not enough, you need to define the variable as built in variable. But seriously, don't do it

Edit: Note, that obviously it hold similarly to local objects, you need (to make sure) to initialise it before you use it!

Lucas
  • 395
  • 1
  • 11