下面是示例数据框
>>> df = pd.DataFrame({'a': [1, 1, 1, 2, 2], 'b':[11, 22, 33, 44, 55]})
>>> df
a b
0 1 11
1 1 22
2 1 33
3 2 44
4 3 55
现在我想根据索引更新/替换与其他字典中的列匹配的 b 值
例如:
match = {1:[111, 222], 2:[444, 555]}
输出:
a b
0 1 111
1 1 222
2 1 33 <-- ignores this bcz not enough values to replace in match dict for 1
3 2 444
4 3 555
提前致谢
最佳答案
这是一种方法。这个想法是按组计算累积计数并使用它来过滤行。使用 itertools.chain
创建单个值数组。最后,使用pd.DataFrame.loc
和 bool 索引来设置值。
from itertools import chain
count = df.groupby('a').cumcount() + 1
m1 = df['a'].isin(match)
m2 = count.le(df['a'].map(match).map(len))
values = list(chain.from_iterable(match.values()))
df.loc[m1 & m2, 'b'] = values
print(df)
a b
0 1 111
1 1 222
2 1 33
3 2 444
4 2 555
关于python - Pandas 替换多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52222676/