具有条件的pandas中两个数据帧的复杂映射操作

时间:2016-12-14 12:30:12

标签: python pandas

我在pandas df中有一张桌子。

id    prod1    prod2    count
1      10       30        100
2      10       20        200
3      20       10        200
4      30       10        100
5      30       40        300

我也在df2中有另一张桌子

product  price   master_product
  1000       1          10
  5000       2          10
  2000       2          20
  9000       5          20
  8000       1          20
  30         3          0
  4000       4          50

检查prod1和prod2是否属于master_product中的值,

如果是的话 我想用我的master_product中最便宜的产品替换我的第一个df中的prod1和prod2。

如果prod1和prod2值与master_product中的值不匹配, 保留原样。

我正在寻找决赛桌。

id    prod1    prod2    count
1      1000    4000        100
2      1000    8000        200
3      8000    1000        200
4      30       1000        100   #since 30 is not in master_product,leave as it is
5      30       40        300

我试图使用.map函数来实现这一目标 但我只能达到这一点。

df['prod1'] = df['prod1'].map(df2.set_index('master_product')['product'])
df['prod2'] = df['prod2'].map(df2.set_index('master_product')['product'])

但它会尝试用df2中master_product中的匹配值替换prod1和prod2中的每个值。

任何想法如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

您可以先df1 price修改master_product price groupby idxmin - 获取最小df1 = df1.loc[df1.groupby('master_product')['price'].idxmin()] print (df1) product price master_product 5 30 3 0 0 1000 1 10 4 8000 1 20 6 4000 4 50 的所有索引:< / p>

dict

为映射创建d = df1.set_index('master_product')['product'].to_dict() print (d) {0: 30, 10: 1000, 20: 8000, 50: 4000}

df.prod1 = df.prod1.map(d).combine_first(df.prod1)
df.prod2 = df.prod2.map(d).combine_first(df.prod2)
print (df)
   id   prod1   prod2  count
0   1  1000.0    30.0    100
1   2  1000.0  8000.0    200
2   3  8000.0  1000.0    200
3   4    30.0  1000.0    100
4   5    30.0    40.0    300

上次map,如果缺少值,请按combine_first添加:

if (!string.IsNullOrEmpty(txbbox.Text)) 
{

  query = "s.date== DateTime.Parse(txbbox.Text)";
}

if (!string.IsNullOrEmpty(txbbox.Text))
{
   query = query + " & (s.type.Contains(txbbox.Text))";
}
相关问题