Pandas如何根据条件对groupby中的行进行分列
Pandas how to divide columns of rows within groupby based on condition
我有数据框
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 组。
在这些组中,我想创建一个新列 target/end。
所以输出将是:
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
最好的方法是什么?
编辑:忽略其他
我们可以 pivot
数据框进行整形,然后使用 eval
计算 target / end
,然后 merge
给定的 df
和 [= 上的评估列17=]
c = ['C1', 'c10']
df.merge(df.pivot(c, 'val_type', 'val').eval('target/end').rename('new'), on=c)
C1 c10 val val_type new
0 1 3 5 target 0.625000
1 1 3 8 end 0.625000
2 1 3 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
你可以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
我有数据框
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 组。 在这些组中,我想创建一个新列 target/end。 所以输出将是:
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
最好的方法是什么?
编辑:忽略其他
我们可以 pivot
数据框进行整形,然后使用 eval
计算 target / end
,然后 merge
给定的 df
和 [= 上的评估列17=]
c = ['C1', 'c10']
df.merge(df.pivot(c, 'val_type', 'val').eval('target/end').rename('new'), on=c)
C1 c10 val val_type new
0 1 3 5 target 0.625000
1 1 3 8 end 0.625000
2 1 3 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
你可以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