arqchicago arqchicago - 10 months ago 37
Python Question

multiply two pandas dataframes

I have two pandas dataframes:

df1

id type NY PA MD
0 90 superurban 0.1 0.1 0.08
1 88 urban 0.1 0.08 0.08
2 75 suburban 0.06 0.04 0.04
3 60 rural 0.04 0.02 0.02


df2

name item
0 NY 1000
1 PA 500
2 MD 250


How can I multiple "item" values in df2 with df1 float values according to state abbreviations? The output should be:

id type NY PA MD
0 90 superurban 100 50 20
1 88 urban 100 40 20
2 75 suburban 60 20 10
3 60 rural 40 10 5

Answer Source

we can do it this way:

In [112]: d1[['NY','PA','MD']] *= d2.set_index('name')['item']

In [113]: d1
Out[113]:
   id        type     NY    PA    MD
0  90  superurban  100.0  50.0  20.0
1  88       urban  100.0  40.0  20.0
2  75    suburban   60.0  20.0  10.0
3  60       rural   40.0  10.0   5.0

Or much better variant from @JohnGalt:

In [118]: d1[d2['name']] *= d2.set_index('name')['item']

In [119]: d1
Out[119]:
   id        type     NY    PA    MD
0  90  superurban  100.0  50.0  20.0
1  88       urban  100.0  40.0  20.0
2  75    suburban   60.0  20.0  10.0
3  60       rural   40.0  10.0   5.0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download