1つ以上の共通の列に基づいて複数のファイル(偶数> 2)をマージする場合、Pythonでの最も効率的なアプローチの1つは「醸造所」を使用することです。マージのためにどのフィールドを考慮する必要があるのか、どのフィールドを保存する必要があるのかを指定することもできます。
import brewery
from brewery
import ds
import sys
sources = [
{"file": "grants_2008.csv",
"fields": ["receiver", "amount", "date"]},
{"file": "grants_2009.csv",
"fields": ["id", "receiver", "amount", "contract_number", "date"]},
{"file": "grants_2010.csv",
"fields": ["receiver", "subject", "requested_amount", "amount", "date"]}
]
すべてのフィールドのリストを作成し、ソース定義を介してデータrecords.Goの起源に関する情報を格納し、フィールドを収集するために、ファイル名を追加します。
for source in sources:
for field in source["fields"]:
if field not in all_fields:
out = ds.CSVDataTarget("merged.csv")
out.fields = brewery.FieldList(all_fields)
out.initialize()
for source in sources:
path = source["file"]
# Initialize data source: skip reading of headers
# use XLSDataSource for XLS files
# We ignore the fields in the header, because we have set-up fields
# previously. We need to skip the header row.
src = ds.CSVDataSource(path,read_header=False,skip_rows=1)
src.fields = ds.FieldList(source["fields"])
src.initialize()
for record in src.records():
# Add file reference into ouput - to know where the row comes from
record["file"] = path
out.append(record)
# Close the source stream
src.finalize()
cat merged.csv | brewery pipe pretty_printer
は素晴らしい作品に参加。入力ファイルはキーでソートする必要があります。また、任意のcsvファイルを読み取ることもできません。具体的には、引用されたフィールド内のコンマは、そのレコードのすべてのフィールドナンバーをシフトします。 – Javier
@Javier:合意しました。これはあなたのコメントを見ていなくても私の答えを更新しました(これはおそらく、編集)。 –