我有两个pandas数据帧:
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
如何根据状态缩写在df2中使用df1浮点值多个“item”值?输出应为:
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
答案 0 :(得分:4)
我们可以这样做:
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
或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
答案 1 :(得分:2)
或者您可以使用mul
;
df1[['NY','PA','MD']]=(df1[['NY','PA','MD']].T.reset_index().drop('index',1)).mul(df2.item,axis='index').T
Out[888]:
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