首页 > 解决方案 > 寻找一种有效的方法来在从其他列的值生成的 pandas 列中生成 dict

问题描述

我正在为 API 字符串准备数据集。数据集有 4-5 百万行。

在准备 API 字符串时,有必要根据数据集的值创建字典。

我有一个工作代码,使用列表理解,效果很好。但是对于数据集,计算时间大约需要 4-5 分钟。

我的问题是,是否有更有效的替代方案。

这是我的代码:

vDf.loc[vDf['type'].isin(simpleattributes),'valuetext'] = [dict(data=data,locale=locale,scope=scope) 
                                                          for data,locale,scope in zip(
                                                              vDf.loc[vDf['type'].isin(simpleattributes),'data']
                                                              ,vDf.loc[vDf['type'].isin(simpleattributes),'locale']
                                                              ,vDf.loc[vDf['type'].isin(simpleattributes),'scope'])]

我正在考虑尝试 numpy where (np.where):

vDf['testdict'] = np.where(vDf['type'].isin(simpleattributes), dict(data=vDf['data'],locale=vDf['locale'],scope=vDf['scope']), "null")

但结果是,返回了一个包含指定列的所有值的列表。

示例输出:

Print VDF testdict
{u'locale': [u'null', u'null', u'null', u'null...
{u'locale': [u'null', u'null', u'null', u'null...
{u'locale': [u'null', u'null', u'null', u'null...
{u'locale': [u'null', u'null', u'null', u'null..

我尝试了与上面类似的代码,但到目前为止,只有列表理解提供了所需的结果。由于我还是 Python 和 Pandas 的新手,我很想知道是否有更有效的方法来生成 dict 值。

提前致谢。

标签: pythonpandas

解决方案


推荐阅读