Мне нужна помощь с выполнением нескольких операций над подгруппами, но я действительно запутался. Я постараюсь быстро описать операции и желаемый результат с комментариями.
(1) Вычислить процентную частоту появления на подгруппу
(2) Появится запись, которой не существует с 0
(3) Изменить порядок записей и столбцов
Предположим, что df ниже как необработанные данные:
df=pd.DataFrame({'store':[1,1,1,2,2,2,3,3,3,3],
'branch':['A','A','C','C','C','C','A','A','C','A'],
'products':['clothes', 'shoes', 'clothes', 'shoes', 'accessories', 'clothes', 'bags', 'bags', 'clothes', 'clothes']})
grouped_df ниже близко к тому, что у меня ум, но я не могу получить желаемый результат.
grouped_df=df.groupby(['store', 'branch', 'products']).size().unstack('products').replace({np.nan:0})
# output:
products accessories bags clothes shoes
store branch
1 A 0.0 0.0 1.0 1.0
C 0.0 0.0 1.0 0.0
2 C 1.0 0.0 1.0 1.0
3 A 0.0 2.0 1.0 0.0
C 0.0 0.0 1.0 0.0
# desirable output: if (1), (2) and (3) take place somehow...
products clothes shoes accessories bags
store branch
1 B 0 0 0 0 #group 1 has 1 shoes and 1 clothes for A and C, so 3 in total which transforms each number to 33.3%
A 33.3 33.3 0 0
C 33.3 0.0 0 0
2 B 0 0 0 0
A 0 0 0 0
C 33.3 33.3 33.3 0
3 B 0 0 0 0 #group 3 has 2 bags and 1 clothes for A and C, so 4 in total which transforms the 2 bags into 50% and so on
A 25 0 0 50
C 25 0 0 0
# (3) rearrangement of columns with "clothes" and "shoes" going first
# (3)+(2) branch B appeared and the the order of branches changed to B, A, C
# (1) percentage calculations of the occurrences have been performed over groups that hopefully have made sense with the comments above
Я пытался обрабатывать каждую группу отдельно, но i) он не принимает во внимание замененные значения NaN, ii) мне следует избегать обработки каждого group, потому что мне нужно будет впоследствии объединить множество групп (этот df - всего лишь пример), поскольку мне нужно будет построить всю группу позже.
grouped_df.loc[[1]].transform(lambda x: x*100/sum(x)).round(0)
>>>
products accessories bags clothes shoes
store branch
1 A NaN NaN 50.0 100.0 #why has it transformed on axis='columns'?
C NaN NaN 50.0 0.0
Надеюсь, мой вопрос имеет смысл. Любое понимание того, что я пытаюсь выполнить, очень приветствуется заранее, большое вам спасибо!