熊猫如何根据条件划分groupby中的行列

时间:2021-06-30 09:19:42

标签: python pandas dataframe data-science data-munging

我有数据框

C1    c10 val val_type
1      3   5   target
1      3   8   end
1      3   9   other
2      8   1   end
2      8   2   target
2      8   9   other

C1、C10 的值创建 3 组。 在这些组中,我想创建一个新的目标/结束列。 所以输出将是:

C1    c10 val val_type   new 
1      3   5   target    0.652
1      3   8   end       0.652
1      3   9   other     0.652
2      8   12  end       0.166
2      8   2   target    0.166
2      8   9   other     0.166

最好的方法是什么?

编辑:忽略其他

2 个答案:

答案 0 :(得分:2)

你可以pivot

s = df.pivot("C1", "val_type", "val")
df["new"] = df["C1"].map(s["target"]/s["end"])
print (df)

   C1  c10  val val_type       new
0   1    3    5   target  0.625000
1   1    3    8      end  0.625000
2   1    5    9    other  0.625000
3   2    8   12      end  0.166667
4   2    8    2   target  0.166667
5   2    8    9    other  0.166667

答案 1 :(得分:0)

我们可以pivot重塑数据框,然后使用eval计算target / end,然后merge给定的df以及{{1}上的评估列}

C1, c10

c = ['C1', 'c10']
df.merge(df.pivot(c, 'val_type', 'val').eval('target/end').rename('new'), on=c)