pandas 替换多个值 [英] pandas replace multiple values

查看:34
本文介绍了 pandas 替换多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是示例数据框

>>> 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值

Now I wanted to update/replace b values that are matched on a column from other dict based on index

例如:

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和布尔索引来设置值.

Here's one way. The idea is to calculate a cumulative count by group and use this to filter rows. Use itertools.chain to create a single array of values. Finally, use pd.DataFrame.loc and Boolean indexing to set values.

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

这篇关于 pandas 替换多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆