【问题标题】:Mapping dictionary of lists to a pandas df将列表字典映射到熊猫 df
【发布时间】:2021-04-30 20:09:24
【问题描述】:

我有一个字典,其中包含一个 id 和该 id 对应值的列表。 我正在尝试将此字典映射到熊猫 df。 df 包含要映射到的相同 id,但它需要按照在 df 中出现的顺序映射该列表中的项目。

例如:

sample_dict = {0:[0.1,0.4,0.5], 1:[0.2,0.14,0.3], 2:[0.2,0.1,0.4]}

df 看起来像: 将字典映射到 df 的输出如下所示: 很抱歉这样输入表格,实际的 df 非常大,而且我对堆栈交换和 pandas 还是很陌生。

最终输出应该只是将 id 列表值映射到播放器,因为它们按顺序显示,因为 df 按 id 排序,然后是播放器

【问题讨论】:

    标签: pandas dataframe dictionary mapping


    【解决方案1】:

    让我们试试explodereindex

    df['new'] = pd.Series(sample_dict).reindex(df.id.unique()).explode().values
    df
    Out[140]: 
       id  Player   new
    0   0       1   0.1
    1   0       2   0.4
    2   0       3   0.5
    3   1       1   0.2
    4   1       2  0.14
    5   1       3   0.3
    6   2       1   0.2
    7   2       2   0.1
    8   2       3   0.4
    

    【讨论】:

    • 我收到错误:AttributeError: 'Series' object has no attribute 'explode'
    • @Redratz 请尝试更新您的熊猫~0.25 后添加的新功能
    猜你喜欢
    • 2020-09-25
    • 2019-09-28
    • 2019-07-30
    • 2019-03-12
    • 1970-01-01
    • 2019-08-20
    • 2021-09-03
    • 2010-12-31
    • 2019-12-13
    相关资源
    最近更新 更多