我有两个Pandas数据帧,即:habitat_family
和{lookupMap
和{
import pandas as pd
import numpy as np
species = ['tiger', 'lion', 'mosquito', 'ladybug', 'locust', 'seal', 'seabass', 'shark', 'dolphin']
families = ['mammal','fish','insect']
lookupMap = {'tiger':'mammal', 'lion':'mammal', 'mosquito':'insect', 'ladybug':'insect', 'locust':'insect',
'seal':'mammal', 'seabass':'fish', 'shark':'fish', 'dolphin':'mammal' }
habitat_family = pd.DataFrame({'id': range(1,11),
'mammal': [101,123,523,562,546,213,562,234,987,901],
'fish' : [625,254,929,827,102,295,174,777,123,763],
'insect': [345,928,183,645,113,942,689,539,789,814]
}, index=range(1,11), columns=['id','mammal','fish','insect'])
habitat_species = pd.DataFrame(0.0, index=range(1,11), columns=species)
# My highly inefficient solution:
for id in habitat_family.index: # loop through habitat id's
for spec in species: # loop through species
corresp_family = lookupMap[spec]
habitat_species.loc[id,spec] = habitat_family.loc[id,corresp_family]
上面嵌套的for循环完成了这项工作。但实际上,我的数据帧的大小是巨大的,使用for循环是不可行的。在
是否有一种更有效的方法来实现这一点,使用maydataframe.apply()
或类似的函数?
编辑:所需的输出habitat_species
是:
你根本不需要任何循环。看看吧:
首先,写得非常好的问题。谢谢。在
我建议为每个系列制作一个数据帧,并在末尾连接: 您需要反转您的
lookupMap
:例如:
^{pr2}$现在每个家庭都要这样做:
还有海螺:
如果您想要具有(family,species)对的列的层次索引,可以考虑将这些家族作为
key
参数传递给concat
。在因为你说过性能很重要:
看来丹赢了一个长传!在
这可能是最通俗的:
相关问题 更多 >
编程相关推荐