поиск промежуточных итогов по столбцам с использованием сводной таблицы в фреймах данных.
df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"], "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"], "C": ["small", "large", "large", "small", "small", "large", "small", "small", "large"], "D": [1, 2, 2, 3, 3, 4, 5, 6, 7]})
print (df)
pd.pivot_table(df, values=['D'], index=['A'], columns=['C', 'B'], aggfunc={'D': np.sum}, margins=True, fill_value=0, margins_name="Total")
following should be the output:
D
C large Total small Total
B one two one two
A
bar 4 7 11 5 6 11
foo 4 0 4 1 6 7
Total 8 7 15 6 12 33