无法使用具有多索引的地图功能将系列注入 pandas 数据框 [英] unable to use map function with multi-index to inject series into pandas dataframe

查看:76
本文介绍了无法使用具有多索引的地图功能将系列注入 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据:

data = {"uid":{"0":"abc123","1":"abc123","2":"abc","3":"abc","4":"efgh"},"comp_id":{"0":1395,"1":2467,"2":4567,"3":1596,"4":111222},"retailer":{"0":"Shmo","1":"Joe","2":"Jon","3":"Sam","4":"Tim"},"price":{"0":7.49,"1":5.17,"2":89.99,"3":13.99,"4":4.98}}
stock = {"uid":{"0":"abc123","1":"abc123","2":"abc","3":"abc","4":"efgh"},"comp_id":{"0":1395,"1":2467,"2":4567,"3":1596,"4":111222},"availability":{"0":"True","1":"True","2":"True","3":"True","4":"True"}}
df = pd.DataFrame(data)
s = pd.DataFrame(stock)
s = s.set_index(['comp_id','uid'])

代码:

df.insert(2, 'availability', df.set_index(['uid','comp_id']).index.map(s['availability']))

错误:

TypeError: 'Series' object is not callable

另一种外观:

for idx in df.set_index(['uid','comp_id']).index:
       map(idx, s['availability'])

目标:

通常,我不得不将一个df的一个序列注入另一个df,并且不想使用merge,然后使用列表推导对col名称进行重新排序.我宁愿使用ordereddict或使用inject + map来操纵基于字典结构的数据框.如果您可以在首次创建数据框时将它们组合在一起,那也将很酷.

Often, I'm having to inject one series from one df into another df and don't want to have to use merge and then reorder col names with a list comprehension. I would rather manipulate the dataframes underlying dictionary structure using ordereddict or use inject + map. If you could combine these when the dataframes are first created, that would be cool too.

推荐答案

尝试一下:

In [174]: vals = df[['uid','comp_id']].set_index(['comp_id','uid']).join(s).values

In [175]: vals
Out[175]:
array([['True'],
       ['True'],
       ['True'],
       ['True'],
       ['True']], dtype=object)

In [176]: df.insert(2, 'availability', vals)

In [177]: df
Out[177]:
   comp_id  price availability retailer     uid
0     1395   7.49         True     Shmo  abc123
1     2467   5.17         True      Joe  abc123
2     4567  89.99         True      Jon     abc
3     1596  13.99         True      Sam     abc
4   111222   4.98         True      Tim    efgh

这篇关于无法使用具有多索引的地图功能将系列注入 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆