LoginSignup
0
0

CSVデータを読み替え表に従って読み替える

Posted at

目的

あるCSVデータを読み替え表に従って、読み替えたい
データが読み替え表にすべて存在する場合は読み替えるが、存在しない場合は読み替えずそのままとする
データの第一列ごと(宅1→宅2→宅3)に読み替える。

参考画像
image.png

コード

grouping.py

import os
import pandas as pd

# import csv

groupcsv = "./settingCsv/読み替え表.csv"
targetcsv = "./settingCsv/注文リスト.csv"

# read file by pandas
gp_pd = pd.read_csv(groupcsv)
tt_pd = pd.read_csv(targetcsv)
gp_pd_count = gp_pd['料理セット'].value_counts()

# output csv

outputcsv = "./targetFolder/test.csv"

# main

## duplicate delete list make
tt_NoDup = tt_pd.drop_duplicates(subset=['宅番'])
gp_NoDup = gp_pd.drop_duplicates(subset=['料理セット'])

for index1, tablelist in tt_NoDup.iterrows():
    # 宅番ごとのデータを取り出す
    targettable = tt_pd.query('宅番 == @tablelist.宅番')
    targettable_tmp = targettable.copy(deep=True) 
    # グルーピング用のリストを取り出す
    for list,count in gp_pd_count.items():
        gp_list = gp_pd.query('料理セット == @list')
        # グルーピング用のリストを1つずつ(中華セット1→中華セット2...)グルーピングできるか確認する
        for index2,gp in enumerate(gp_list.iterrows()):
            targettable_check = targettable_tmp.query('注文料理 == @gp[1][1]')
            if not targettable_check.empty:
                targettable_tmp.drop(targettable_tmp[targettable_tmp['注文料理'] == gp[1][1]].index, inplace=True)
                if index2 == (len(gp_list) - 1):
                    targettable_1column = targettable['宅番'][:-1]
                    targettable_tmp2 = {'宅番':targettable_1column.iloc[-1],'注文料理':gp[1][0]}
                    targettable_tmp = pd.concat([targettable_tmp, pd.DataFrame([targettable_tmp2])], ignore_index=True)
                    targettable = targettable_tmp.copy(deep=True) 
            else:
                targettable_tmp = targettable.copy(deep=True) 
                break
    if index1 == 0:
        targettable.to_csv(outputcsv, index = False)
    else:
        targettable.to_csv(outputcsv, index = False, mode='a', header=False)



注文リスト.csv

宅番,注文料理
宅1,天ぷら
宅1,とんかつ
宅1,親子丼
宅1,肉じゃが
宅1,カルビ
宅1,ミスジ
宅1,牛タン
宅1,ラーメン
宅2,ラタトゥイユ
宅2,キャロットラペ
宅2,酢豚
宅2,ラーメン
宅2,青椒肉絲
宅2,八宝菜
宅2,ご飯
宅3,棒棒鶏
宅3,八宝菜
宅3,天ぷら

読み替え表.csv

料理セット,料理
日本食セット2,天ぷら
日本食セット2,とんかつ
日本食セット2,味噌汁
日本食セット1,親子丼
日本食セット1,肉じゃが
中華セット3,ラーメン
中華セット3,青椒肉絲
中華セット2,麻婆豆腐
中華セット2,回鍋肉
中華セット1,棒棒鶏
中華セット1,八宝菜
焼肉セット2,サーロイン
焼肉セット2,ホルモン
焼肉セット1,カルビ
焼肉セット1,ミスジ
焼肉セット1,牛タン
フランス料理セット1,ラタトゥイユ
フランス料理セット1,キャロットラペ

出力データ

test.csv

宅番,注文料理
宅1,天ぷら
宅1,とんかつ
宅1,ラーメン
宅1,焼肉セット1
宅1,日本食セット1
宅2,酢豚
宅2,八宝菜
宅2,ご飯
宅2,中華セット3
宅2,フランス料理セット1
宅3,天ぷら
宅3,中華セット1

その他

データベースやほかのライブラリを使えばこんなに深い階層にならないと思います。
直した方がよいですが、一旦このままとします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0