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?

More than 1 year has passed since last update.

Databricks ( Spark )にて createDataFrame メソッド利用時の LENGTH_SHOULD_BE_THE_SAME エラーへの対応方法

Posted at

概要

Databricks (Spark) で createDataFrame メソッドを使用する際に遭遇するLENGTH_SHOULD_BE_THE_SAMEエラーについての解決策を紹介します。このエラーは、テスト時に変数からデータフレームを生成しようとした際に発生することがあります。

PySparkValueError: [LENGTH_SHOULD_BE_THE_SAME] obj and fields should be of the same length, got 1 and 3.

image.png

エラーの原因は、データを定義する変数のリスト内に別のリストが定義されていることにあります。コピー&ペーストの操作ミスにより、このような構造が作成されることがあります。この問題を解決するには、リストをネストしないように注意してください。

# 修正前
data_001 = [
    [
        {
            'str_col': 'abc',
            'int_col': 123,
            'date_col': datetime.date(2020, 1, 1),
        },
    ]
]

# 修正後
data_001 = [
    {
        'str_col': 'abc',
        'int_col': 123,
        'date_col': datetime.date(2020, 1, 1),
    },
]

エラーの発生方法と対応方法

エラーの発生方法

import datetime

schema = '''
str_col string,
int_col integer,
date_col date
'''

data_001 = [
    [
        {
            'str_col': 'abc',
            'int_col': 123,
            'date_col': datetime.date(2020, 1, 1),
        },
    ]
]

df = spark.createDataFrame(
    data_001,
    schema,
)

df.display()
PySparkValueError: [LENGTH_SHOULD_BE_THE_SAME] obj and fields should be of the same length, got 1 and 3.

image.png

エラーへの対応方法

import datetime

schema = '''
str_col string,
int_col integer,
date_col date
'''

data_001 = [
        {
            'str_col': 'abc',
            'int_col': 123,
            'date_col': datetime.date(2020, 1, 1),
        },
]

df = spark.createDataFrame(
    data_001,
    schema,
)

df.display()

image.png

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?