不建议使用Pandas Lookup-优雅高效的替代方案 [英] Pandas Lookup to be deprecated - elegant and efficient alternative

查看:41
本文介绍了不建议使用Pandas Lookup-优雅高效的替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以后的版本中将不建议使用Pandas查找功能.如警告所示,建议使用.melt和.loc作为替代.

The Pandas lookup function is to be deprecated in a future version. As suggested by the warning, it is recommended to use .melt and .loc as an alternative.

df = pd.DataFrame({'B': ['X', 'X' , 'Y', 'X', 'Y', 'Y', 'X', 'X', 'Y', 'Y', 'X', 'Y'],
                   'group': ["IT", "IT", "IT", "MV", "MV", "MV", "IT", "MV", "MV", "IT", "IT", "MV"]})

a = pd.concat([df, df['B'].str.get_dummies()], axis=1).groupby('group').rolling(3, 
                   min_periods=1).sum().sort_index(level=1).reset_index(drop=True)               

df['count'] = a.lookup(df.index, df['B'])

# Output Warning:
# <ipython-input-16-e5b517460c82>:7: FutureWarning: The 'lookup' method is deprecated and will be
# removed in a future version. You can use DataFrame.melt and DataFrame.loc as a substitute.

但是,替代方法似乎不太优雅且较慢:

However, the alternative appears to be less elegant and slower:

b = pd.melt(a, value_vars=a.columns, var_name='B', ignore_index=False)
b.index.name='index'
df.index.name='index'
df = df.merge(b, on=['index','B'])
df

有没有更优雅,更有效的方法呢?

Is there a more elegant and more efficient approach to this?

谢谢.

推荐答案

看起来,您可以直接使用索引来分配新值.

It looks like, you can just use the index to assign new values.

dfn = df.set_index('B', append=True)
dfn['count'] = a.stack()

这篇关于不建议使用Pandas Lookup-优雅高效的替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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