Python - パンダを使用した文字列と追加の列に基づいて数量を集計します

okwaves2024-01-25  7

次のようなデータを含むデータセットがあります:

Month, Year, Quantity Sold, Product Name
11, 2017, 13, "Creatine Powder Supplement - 500g"
11, 2017, 10, "Gummies 1 bag"
11, 2017, 12, "Creatine Powder Supplement - 1000g"
11, 2017, 15, "Creatine Powder Supplement - 1500g"
11, 2017, 11, "Glucosamine - 500g"
11, 2017, 23, "Glucosamine - 1500g"
12, 2017, 17, "Creatine Powder Supplement - 1000g"
12, 2017, 24, "Glucosamine - 500g"
12, 2017, 13, "Glucosamine - 1500g"
1, 2018, 16, "Creatine Powder Supplement - 500g"
1, 2018, 13, "Creatine Powder Supplement - 1000g"
1, 2018, 10, "Gummies 1 bag"
1, 2018, 11, "Glucosamine - 500g"
1, 2018, 21, "Glucosamine - 1500g"

販売された製品の総重量を月と年に分けて計算したいのですが、そのためには「製品名」から製品の重量を抽出する必要があります。列に「販売数量」を掛けます。列に関連商品の合計を入力します。

目的の出力 (最初の行の販売総重量のみを計算しました):

Matched data set:

Month, Year, Product Name, Total Weight Sold
11, 2017, Creatine Powder Supplement, 41000
11, 2017, Glucosamine, <total>
12, 2017, Creatine Powder Supplement, <total>
12, 2017, Glucosamine, <total>
1, 2018, Creatine Powder Supplement, <total>
1, 2018, Glucosamine, <total>

これに加えて、パターン <number>g で終わらない商品については、レビューできるように別のデータセットに出力したいと考えています。

UNmatched data set:

Month, Year, Quantity Sold, Product Name
11, 2017, 10, "Gummies 1 bag"
1, 2018, 10, "Gummies 1 bag"

str.extract の使用を考えていますが、計算を行って、その結果の計算された合計を他の行に合計する方法が完全にわかりません。同じプロダクトを新しい DataFrame などに追加します。

ありがとう



------------------------

私が考える最も簡単な解決策は次のとおりです。

product_data = df['Product Name'].str.extract('(?P<name>\w+) - (?P<weight>\d+)g')
invalid_rows = df[product_data['weight'].isnull()]
product_data.drop(labels=invalid_rows.index, inplace=True)
df.drop(labels=invalid_rows.index, inplace=True)
df['Product Name'] = product_data['name']
df['Total'] = product_data['weight'].astype(np.int32) * df['Quantity Sold']
print(df.groupby(['Month', 'Year', 'Product Name']).sum()['Total'].reset_index())
print()
print(invalid_rows)

どの出力

  Month  Year Product Name  Total
0     1  2018     Creatine  21000
1     1  2018  Glucosamine  37000
2    11  2017     Creatine  41000
3    11  2017  Glucosamine  40000
4    12  2017     Creatine  17000
5    12  2017  Glucosamine  31500

   Month  Year Quantity Sold     Product Name
1     11  2017            10  "Gummies 1 bag"
11     1  2018            10  "Gummies 1 bag"

2

これには、一致しないものを個別に出力するための 2 番目の部分が欠けていると思いますが、これは最初の部分の答えです。のサンプル データ セットを更新します。一致しないデータを含める質問。

– ジェイウプ

2020 年 9 月 4 日 19:33

とても近いです!製品名には複数の単語が含まれることがよくあります。反映するために編集しました。提供された正規表現はそれをキャプチャしません。

– ジェイウプ

2020 年 9 月 8 日 23:39



------------------------

これは Python ソリューションです。エラーが書き込まれます行を出力ファイルに書き込み、適切な行を端末に書き込みます。

from collections import defaultdict
import re

d = defaultdict(int)

with open('f0.txt', 'r') as f, open('err.txt', 'w') as fout:
    fout.write(f.readline()) # print header to err.txt

    for row in f:
        row = row.rstrip()
        if re.search(r'- \d+g"', row):
            month, yr, qty, product = row.split(', ')
            product = product.replace('g', '').replace('"', '')
            name, grams = product.split(' - ')
            key = ','.join([month, yr, name])
            d[key] += int(qty) * int(grams)
        else:
            # handle this row (that doesn't have a Product and weight)
            fout.write(row + '\n')

print(','.join(['Month', 'Year', 'Product Name', 'Total Sold']))

for key, total in d.items():
    print(f'{key},{total}')

端末に出力:

Month,Year,Product Name,Total Sold
11,2017,Creatine,41000
11,2017,Glucosamine,40000
12,2017,Creatine,17000
12,2017,Glucosamine,31500
1,2018,Creatine,21000
1,2018,Glucosamine,37000

err.txt に出力します:

Month, Year, Quantity Sold, Product Name
11, 2017, 10, "Gummies 1 bag"
1, 2018, 10, "Gummies 1 bag"

総合生活情報サイト - OKWAVES
総合生活情報サイト - OKWAVES
生活総合情報サイトokwaves(オールアバウト)。その道のプロ(専門家)が、日常生活をより豊かに快適にするノウハウから業界の最新動向、読み物コラムまで、多彩なコンテンツを発信。