将列表字典映射到 pandas df
Mapping dictionary of lists to a pandas df
我有一本字典,其中包含一个 ID 和该 ID 对应值的列表。
我正在尝试将这本字典映射到 pandas 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 的输出如下所示:
很抱歉像这样输入 table,实际 df 非常大,我对堆栈交换和 pandas.
还是个新手
最终输出应该只是将 id 列表值映射到玩家,因为他们按顺序出现,因为 df 按 id 排序,然后是玩家
让我们尝试 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
我有一本字典,其中包含一个 ID 和该 ID 对应值的列表。 我正在尝试将这本字典映射到 pandas 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 看起来像:
最终输出应该只是将 id 列表值映射到玩家,因为他们按顺序出现,因为 df 按 id 排序,然后是玩家
让我们尝试 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