0

If i am writing this function:

def find_val (df, name, name_val):

    value = df[ df[str(name)].map(name).eq(name_val) ]
    return value

Here the name is same but in different form. First as name of column in dataframe and second the same name is in the form of dictionary. I am trying to avoid this:

def find_val (df, name_col, name_dict, name_val):

# here name_col and name_dict have the same name. for example 'brands' then brands is a column in my df as well a seperate dictionary named brands.

Is this possible to avoid?

Ajax
  • 125
  • 7
  • 1
    It doesn't matter how you called your dictionary, it's just a variable name. It doesn't worth the effort of using `name` once as a dict and once as a string, just pass 2 parameters. – Guy Mar 11 '20 at 13:50
  • @Guy just looking for possibilities. is it possible to do? and also it must be defined like this. can't have two diferent names. it must be the same – Ajax Mar 11 '20 at 13:54
  • 1
    https://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-variable-given-its-name-in-a-string is an example, but IMO you shouldn't. – Guy Mar 11 '20 at 13:56
  • you can use a separate param as suggested above instead like: `d = {'drinks':d_1,'brands':d_2}` ; `def find_val (df,name,key,name_val): return df[ df[str(name)].map(d[key]).eq(name_val)]` ; `find_val(df,'drinks','drinks','cola')` - from your previous example maybe.... – anky Mar 11 '20 at 13:58
  • @anky_91 okay i will give it a try. thanks – Ajax Mar 11 '20 at 14:03
  • @anky_91 i am trying here that i don't have to write `drinks` two times in a function parameter. – Ajax Mar 11 '20 at 14:07
  • 1
    @Arpit as @Guy says, possible but not recommended,instead pass another param , however, test with:`d = {'drinks':d_1,'brands':d_2}`; `def find_val (df, name,name_val): return df[ df[str(name)].map(d[locals()['name']]).eq(name_val) ]`;`find_val(df,'drinks','cola')` – anky Mar 11 '20 at 14:10
  • @anky_91 it must be like this. i know it's not the ideal way and code is giving keyerror showing the complete dictionary. – Ajax Mar 11 '20 at 14:19
  • Works fine for me in my system, just tested with your previous question dataset ,`keyerror` means the column which you are trying to pass isn't present in the dataframe or may be the actual key in the dataframe has some unwanted spaces. – anky Mar 11 '20 at 14:19
  • @anky_91 you made another dictionary, where all the dictinaries are stored. – Ajax Mar 11 '20 at 14:22
  • Yes, with that it works fine for me :) can you test with data from the previous question – anky Mar 11 '20 at 15:01

0 Answers0