1
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?

More than 3 years have passed since last update.

DatabricksでExcel ファイルをDelta Lakeに保存する

Last updated at Posted at 2022-01-31

はじめに

Excelで業務を行なっていることって、まだまだ沢山ありますよね。そのような大量のデータをいち早くデータ解析に回すにはということで試してみました。

今回は複数のExcelファイルを一度に読み取って Delta Lakeに保存するまでを試してみます。

データソース

サンプルデータとして、Blob Storage上に5つのExcelをアップロードしました。
データは、generatorで作成した100行のデータでカラムは全て一緒ですが、バラバラのカラム名であっても読み取れるようにしております。

こんなデータ

image.png

ライブラリーのインストール

Excelファイルを読み込むために、ライブラリーをインストールしておきます。

%pip install openpyxl

Excelファイルの読み込み(1ファイルの場合)

1ファイルだけであればこちらの方法で読み取れます。今回 storage_pathには blobストレージを指定してますが、今回はその部分は省略してます。

import pandas
import io

df = spark.read.format("binaryFile").load(storage_path + "/data01.xlsx")

bstream = io.BytesIO(df.select("content").collect()[0].content)
pdf = pandas.read_excel(bstream)
pdf 

image.png

複数のExcelファイル読み込み & Delta Lake保存

それでは、本題である複数のExcelファイルを一気に読み取ってみたいと思います。
またDelta Lakeに保存しておき、その後処理をしやすくしておきます。

import io
import pandas as pd 
from pyspark.sql.functions import *

# 保存する DeltaLake Directory path 
delta_path = '\<保存先のパス>'

# Data load by binary
df1 = spark.read.format("binaryFile").load(storage_path)
  
# binary contents をロードして中身を読み込み、DeltaLakeに書き込む
def excel_to_df(ps):
  for i in range(ps.count()):
    bstream = io.BytesIO(ps.collect()[i].content)
    pdf = pd.read_excel(bstream)
    df = spark.createDataFrame(pdf)
    df.write.mode('append').option("mergeSchema", "true").save(delta_path)

excel_to_df(df1.select('content'))

これで、Excelファイルを読み込み、DeltaLakeに保存出来ました。
確認してみましょう。

image.png

500行のデータになってますね。

Delta Lakeに保存出来たのであとはデータ分析や、機械学習などで簡単に利用できます。

image.png

1
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
1
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?