简体   繁体   中英

access dictionary inside a function using python

so the problem I am stuck with is, I am unsure of how to call a dictionary inside a function.

>>> play = pd.DataFrame(play)
>>> play
      No      Yes
0  Wednesday   Monday
1   Thursday  Tuesday
2   Saturday   Friday
>>> days = 'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'

>>> newdict = {}
>>> numbincrease = 0
>>> for i in days:
        newdict[i] = numbincrease
        numbincrease = numbincrease + 1


>>> print(newdict)
{'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5}

So I want to convert the days to numbers, the output should be able to iter over all the columns and all the rows and read the dictionary and replace with the appropriate value from the dictionary used in the program. The output should look like,

>>> play
      No      Yes
0     2        0
1     3        1
2     5        4  

I have searched for many ways to do this, but it doesn't seem to work. I have no idea of how to call a function to iterate over each column and apply call dictionary to that value and continue with next row or column. Please help, Thank you

pd.DataFrame.applymap can be used to apply a function to every value in a dataframe. In this case, the appropriate function is dict.get .

Note, as below, you can efficiently map days to integers using a dictionary comprehension with enumerate .

days = ('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')

daymap = {v: k for k, v in enumerate(days)}

res = df.applymap(daymap.get)

print(res)

   No  Yes
0   2    0
1   3    1
2   5    4

Try this, .applymap iterates through every item in a dataframe
play.applymap(lambda x: newdict[x])


Edit: with advice from @jpp:
play.applymap(newdict.get)

You can do so:

play = play.replace(newdict)

The difference between replace and applymap is that when an element in your df is not in the dictionary, with replace the element will stay as it is:

df:

         No       Yes
  Wednesday    Monday
   Thursday   Tuesday
      a day    Friday 

with replace :

      No    Yes
0      2      0
1      3      1
2  a day      4

With applymap you will have NaN :

    No  Yes
0  2.0    0
1  3.0    1
2  NaN    4 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM