我有一个Pandas dataframe,它有两个键列,我想确保表中存在这些键的笛卡尔积(因为我必须绘制一个包含所有组合的2D图)。我很难想出一个相当简单和惯用的方法来做这件事。在
例如,我从这张桌子开始,给出了水果和蔬菜的组合,以及它们在一起的味道:
combo fruit veg
0 tasty apple carrot
1 yucky banana carrot
2 tasty banana lettuce
3 yucky lemon lettuce
我想以这个表格结束,在这个表格中,所有可能的组合都会出现:
^{pr2}$我找到了最好的方法:
import pandas as pd
# Initial data
df=pd.DataFrame(dict(fruit=['apple','banana','banana','lemon'],
veg=['carrot','carrot','lettuce','lettuce'],
combo=['tasty','yucky','tasty','yucky']))
# Solution starts here
veg=df.groupby('veg').size().reset_index()
fruit=df.groupby('fruit').size().reset_index()
fruit[0] = veg[0] = 0 #use this dummy column for the join to work!
cartesian = pd.merge(fruit, veg, how='outer', on=0)
del cartesian[0]
all_combos = pd.merge(cartesian, df, how='left')
all_combos[ pd.isnull(all_combos.combo) ] = 'UNKNOWN'
我想应该有一种更简单、更不容易出错的方法来做到这一点。。。有什么建议吗?在
如果有人能告诉我如何使用和不使用包含fruit
和veg
列的多索引,我将特别感谢,因为我对如何使用索引做这件事感到困惑。根据我的SQL经验,我认为这正是索引的目的。在
在这个答案之后的某个时候,我将
cartesian_product
添加到pandas中,并且在添加了{a1}之后不久(按照another question中的建议)。这样可以实现以下更有效的简化:旧的答案是:
如果您使用水果和蔬菜作为索引,那么您可以使用^{} *创建
^{pr2}$MultiIndex
到{a4},方法是:最棘手的是抓住所有可能的水果/蔬菜的正确多重指数:
然后您可以通过以下方法重新编制索引:
*如果
itertools.product
不够快,请考虑使用this numpy implemention注意:这个实现是在
pandas.tools.util.cartesian_product
中扩展的,它现在支持更多的数据类型(并且在MultiIndex.from_product
中暗地使用)。相关问题 更多 >
编程相关推荐