Pandas シリーズを CSV ファイルにエクスポートする 4 つの方法は次のとおりです。

(1)索引も見出しもない

import pandas as pd

ser = pd.Series(["value_1", "value_2", "value_3", ...])
ser.to_csv(r"Path to store the CSV file\File Name.csv", index=False, header=False)

(2)索引はないが見出しはある

import pandas as pd

ser = pd.Series(["value_1", "value_2", "value_3", ...])
ser.rename("header name", inplace=True)
ser.to_csv(r"Path to store the CSV file\File Name.csv", index=False, header=True)

(3)索引あり、ヘッダーなし

import pandas as pd

ser = pd.Series(["value_1", "value_2", "value_3", ...])
ser.to_csv(r"Path to store the CSV file\File Name.csv", index=True, header=False)

(4)索引と見出し付き

import pandas as pd

ser = pd.Series(["value_1", "value_2", "value_3", ...])
ser.rename("header name", inplace=True)
ser.to_csv(r"Path to store the CSV file\File Name.csv", index=True, header=True)

PandasシリーズをCSVファイルにエクスポートする手順

ステップ1: Pandasシリーズを作成する

まず、CSV ファイルにエクスポートする Pandas シリーズを作成します。

たとえば、5 つの製品の名前を含むシンプルな Pandas シリーズを作成します。

import pandas as pd

ser = pd.Series(["computer", "keyboard", "printer", "monitor", "tablet"])

print(ser)

Python でコードを実行すると、次のシリーズが得られます。

PandasシリーズをCSVファイルにエクスポートする方法 1

ステップ2: CSVファイルのパスを取得する

次に、CSV ファイルを保存するパスを取得します。

たとえば、CSV ファイル (ファイル名が「Products」、ファイル タイプが「.csv」) が次のパスに保存されるとします。

C:\Users\Ron\Desktop\Products.csv

ステップ3: PandasシリーズをCSVにエクスポートする

Pandas シリーズを CSV ファイル (インデックスなし、ヘッダーなし) にエクスポートするには、次のテンプレートを使用します。

import pandas as pd

ser = pd.Series(["value_1", "value_2", "value_3", ...])
ser.to_csv(r"Path to store the CSV file\File Name.csv", index=False, header=False)

私たちの例:

import pandas as pd

ser = pd.Series(["computer", "keyboard", "printer", "monitor", "tablet"])
ser.to_csv(r"C:\Users\Ron\Desktop\Products.csv", index=False, header=False)

Python でコードを実行すると (パスに合わせて調整)、シリーズ データを含む次の CSV ファイルが生成されます。

PandasシリーズをCSVファイルにエクスポートする方法 2

Pandas シリーズを CSV にエクスポートする追加シナリオ

索引はないがヘッダーはある

シリーズの列名を表す ‘product_name’ のヘッダーを追加するには:

import pandas as pd

ser = pd.Series(["computer", "keyboard", "printer", "monitor", "tablet"])
ser.rename("product_name", inplace=True)
ser.to_csv(r"C:\Users\Ron\Desktop\Products.csv", index=False, header=True)

新しい列名の結果:

PandasシリーズをCSVファイルにエクスポートする方法 3

インデックスあり、ヘッダーなし

この場合は、単に header=False を設定します。

import pandas as pd

ser = pd.Series(["computer", "keyboard", "printer", "monitor", "tablet"])
ser.to_csv(r"C:\Users\Ron\Desktop\Products.csv", index=True, header=False)

インデックス付きのエクスポートされたシリーズ:

PandasシリーズをCSVファイルにエクスポートする方法 4

索引と見出し付き

インデックスとヘッダー付き:

import pandas as pd

ser = pd.Series(["computer", "keyboard", "printer", "monitor", "tablet"])
ser.rename("product_name", inplace=True)
ser.to_csv(r"C:\Users\Ron\Desktop\Products.csv", index=True, header=True)

結果:

PandasシリーズをCSVファイルにエクスポートする方法 5