0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

csvを特定の順番で並べ替え

Posted at

csvモジュールのパターン

import csv

# 並び替えたい順序
order = [2, 4, 3, 1]

# CSVファイルの読み込み
with open('input.csv', newline='', encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile)
    rows = [row for row in reader]

# 並べ替え(orderの順に並ぶようにフィルタ&ソート)
sorted_rows = [row for oid in order for row in rows if int(row['id']) == oid]

# 出力
with open('output_csv.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=reader.fieldnames)
    writer.writeheader()
    writer.writerows(sorted_rows)

pandasモジュールのパターン

import pandas as pd

# 並び替えたい順序
order = [2, 4, 3, 1]

# CSV読み込み
df = pd.read_csv('input.csv')

# 並べ替え(orderの順にidをカテゴリ化して並び替え)
df['id'] = pd.Categorical(df['id'], categories=order, ordered=True)
df_sorted = df.sort_values('id')

# 出力
df_sorted.to_csv('output_pandas.csv', index=False)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?