Assigning content of a pandas DataFrame cell based on some condition without using loops

I have a pandas DataFrame df with the following content:

Serial N       voltage       current
   B              10            nan
   B              10            nan
   C              12            nan
   D              40            nan
   .               .             .
   AB             12            nan

I also have the following dictionary which contains the current values as following (my key here is the serial number):

my_dict={A:0.6,B:0.2, ...,AB:0.2}

I would like to store the content of my dictionary into the dataFrame column "current" based on the dictionary. I can have multiple serial number in the dataFrame df with the same value. I would like to do so without using loops if possible. I tried this:

for k,v in my_dict.items():
   if df["Serial N"]==k:           

But it does not to work, Because I do not have the position of the rows (I can have several Serial number with same value; example: B in the Serial N column) where the condition is satisfied. How can I do this without a loop?


You can use map:

print df
  Serial N  voltage  current
0        B       10      NaN
1        B       10      NaN
2        C       12      NaN
3        D       40      NaN
4       AB       12      NaN

print my_dict
{'A': 0.6, 'B': 0.2, 'AB': 0.2}

df['current'] =  df['Serial N'].map(my_dict)
print df
  Serial N  voltage  current
0        B       10      0.2
1        B       10      0.2
2        C       12      NaN
3        D       40      NaN
4       AB       12      0.2

Need Your Help

How to create Revit Add-In DLL from Python

python add-in revit

I did a dumb thing. I got all excited about Revit 2014 allowing macros in Ruby, installed RevitRubyShell, and wrote what is going to become an add-in.

Why should I NOT deploy my website or webapp to the root of a domain in IIS? web-applications web iis-7.5 web-deployment

Quite a few years ago, I remember that I struggled with a multiple site under one domain situation, where one of the sites was placed in the root.