у меня есть дф
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 для всех комбинаций ключевых значений.
Ожидаемый результат
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
Похоже, вы должны написать код...