将列表字典映射到熊猫 df

时间:2021-01-27 01:11:20

标签: pandas dataframe dictionary mapping

我有一个字典,其中包含一个 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 看起来像: enter image description here 将字典映射到 df 的输出如下所示: enter image description here 很抱歉像这样输入表格,实际 df 非常大,而且我还是堆栈交换和熊猫的新手。

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

1 个答案:

答案 0 :(得分:2)

让我们用 explode 试试 reindex

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