我有一个这样的 df:
ID
0 123
1 123
2 123
3 123
4 123
5 123
6 456
7 456
8 456
9 123
我想使用 dict d 添加一个带有 map
函数的新列:d = {'123': [1, 2, 3, 1, 2, 1, 5], '456': [1, 2, 1]}
预期输出: ID Count
0 123 1
1 123 2
2 123 3
3 123 1
4 123 2
5 123 1
6 456 1
7 456 2
8 456 1
9 123 5
但是 df.ID.map(d)
返回:0 [1, 2, 3, 1, 2, 1, 5]
1 [1, 2, 3, 1, 2, 1, 5]
2 [1, 2, 3, 1, 2, 1, 5]
3 [1, 2, 3, 1, 2, 1, 5]
4 [1, 2, 3, 1, 2, 1, 5]
5 [1, 2, 3, 1, 2, 1, 5]
6 [1, 2, 1]
7 [1, 2, 1]
8 [1, 2, 1]
9 [1, 2, 3, 1, 2, 1, 5]
提前感谢您的帮助!
最佳答案
您可以使用 groupby
+ apply
:
df.groupby('ID').apply(lambda g: pd.Series(d[g.name]))
例子:>>> df['Count'] = df.groupby('ID').apply(lambda g: pd.Series(d[g.name])).to_list()
>>> df
ID Count
0 123 1
1 123 2
2 123 3
3 123 1
4 123 2
5 123 1
6 456 1
7 456 2
8 456 1
编辑。无序输入的变体:(df.join(df.groupby('ID').apply(lambda g: pd.Series(d[g.name],
name='Count',
index=g.index))
.droplevel(0))
)
输出: ID Count
0 123 1
1 123 2
2 123 3
3 123 1
4 123 2
5 123 1
6 456 1
7 456 2
8 456 1
9 123 5
关于pandas - 如何使用 map 函数使用包含嵌套列表的 dict 重新映射数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69209736/