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?

ファイルの出力(Python Pandas)

0
Posted at

はじめに

前回は以下記事を書きました。

今回はファイル出力です。CSVとExcelへの出力を試してみます。
※Power Queryは「閉じて適用」を行うことで、データをPower Queryエディター外に出力できるため、今回はPython Pandasのみです。

以下の辞書型のデータを今回は使用します。

キー
商品 list ['ノートパソコン', 'スマートフォン', 'デスクチェア']
単価 list [120000,80000,15000]
個数 list [2,1,3]
合計 list [240000,80000,45000]

CSVファイルへの出力

CSVへの出力は、to_csv関数を使用します。

import pandas as pd

data={
    '商品':['ノートパソコン','スマートフォン','デスクチェア'],
    '単価':[120000,80000,15000],
    '個数':[2,1,3],
    '合計':[240000,80000,45000],
}
df = pd.DataFrame(data)
df.to_csv(r'Data\Shopping.csv' ,header=True,encoding='utf-8-sig',index=False)   
df.to_csv(r'Data\Shopping.csv' ,header=False, index=False, mode='a')     

DataFrameクラスを使用してデータをdfのデータフレームに格納します。
to_csv関数により、Shopping.csvにデータを出力します。

  • encodingは書き込む際に使用する文字コードを指定
  • headerとindexは列名とインデックスを出力するかどうかをそれぞれ指定
  • modeは'w'が上書き、'a'が追記

Excelファイルへの出力

Excelへの出力はto_excel関数を使用します。

import pandas as pd

data={
    '商品':['ノートパソコン','スマートフォン','デスクチェア'],
    '単価':[120000,80000,15000],
    '個数':[2,1,3],
    '合計':[240000,80000,45000],
}
df = pd.DataFrame(data)
df.to_excel(r'Data\Shopping.xlsx',sheet_name="シート1",header=True,index=False)

DataFrameクラスを使用してデータをdfのデータフレームに格納します。
to_excel関数により、Shopping.xlsxにデータを出力します。

  • sheet_nameは書き出すシートのシート名を指定
  • headerとindexは列名とインデックスを出力するかどうかをそれぞれ指定

to_excel関数は既存ファイルへの追記はできません。
データフレームを連結してから書き出しを行います。

次回の内容

今度はPython Pandasで列と行の操作をしてみたいと思います。

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?