我有一个df
Key1 Key2 Condition Value1 Value2
K1 K2 1 10 202
K1 K2 2 610 206
K1 K2 3 130 250
K11 K21 1 150 270
K11 K21 3 510 20
K13 K23 2 32 5
现在我需要所有条件的标志1,2,3所有键值组合
- 例如,对于K1,K2具有所有3个条件1、2、3和3行,每个条件对应一行。所以所有条件的标志都是Yes
- 钥匙K11、K21只有条件1和条件3,缺少条件2。因此,1和3的标志将是肯定的
- 钥匙K13、K23只有条件2,条件1和3缺失。条件2的标志将为yes
预期输出
Key1 Key2 Condition1 Condition2 Condition3
K1 K2 Yes Yes Yes
K11 K21 Yes No Yes
K13 K23 No Yes No
使用DataFrame.pivot_table
和DataFrame.notna
来测试未丢失的值和DataFrame.add_prefix
布尔值的DataFrame
:
df = (df.pivot_table(index=['Key1','Key2'], columns='Condition', aggfunc='size')
.notna()
.add_prefix('Condition'))
print (df)
Condition Condition1 Condition2 Condition3
Key1 Key2
K1 K2 True True True
K11 K21 True False True
K13 K23 False True False
如果需要yes, no
值,则使用numpy.where
:
df1 = pd.DataFrame(np.where(df, 'Yes','No'), index=df.index, columns=df.columns)
print (df1)
Condition Condition1 Condition2 Condition3
Key1 Key2
K1 K2 Yes Yes Yes
K11 K21 Yes No Yes
K13 K23 No Yes No
最后,如果您需要MultiIndex
到列:
df1 = df1.reset_index().rename_axis(None, axis=1)
print (df1)
Key1 Key2 Condition1 Condition2 Condition3
0 K1 K2 Yes Yes Yes
1 K11 K21 Yes No Yes
2 K13 K23 No Yes No