task1/count_sum_pandas.py

37 lines
1.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# count_sum_pandas.py
import pandas as pd
def count_sum(df: pd.DataFrame) -> pd.DataFrame:
"""
Функция суммирует количество по каждому продукту.
Параметры:
df : pd.DataFrame
Входной DataFrame с колонками 'Дата', 'Товар', 'Количество'
Возвращает:
pd.DataFrame
DataFrame с суммой по каждому товару.
Колонка 'Товар' становится индексом.
"""
# Группируем по столбцу 'Товар' и суммируем 'Количество'
result = df.groupby('Товар', as_index=True)['Количество'].sum().to_frame()
return result
# Пример использования
if __name__ == "__main__":
# Пример данных
data = {
'Дата': ['07.05.2022', '07.05.2022', '08.05.2022', '08.05.2022'],
'Товар': ['Банан', 'Хлеб', 'Банан', 'Хлеб'],
'Количество': [30, 10, 40, 8]
}
df_input = pd.DataFrame(data)
# Вызов функции
df_output = count_sum(df_input)
print(df_output)