当前位置: 首页 > 知识库问答 >
问题:

将Pandas数据帧转换为Spark数据帧错误

公孙成仁
2023-03-14

我正在尝试将熊猫DF转换为Spark one。测向头:

10000001,1,0,1,12:35,OK,10002,1,0,9,f,NA,24,24,0,3,9,0,0,1,1,0,0,4,543
10000001,2,0,1,12:36,OK,10002,1,0,9,f,NA,24,24,0,3,9,2,1,1,3,1,3,2,611
10000002,1,0,4,12:19,PA,10003,1,1,7,f,NA,74,74,0,2,15,2,0,2,3,1,2,2,691

代码

dataset = pd.read_csv("data/AS/test_v2.csv")
sc = SparkContext(conf=conf)
sqlCtx = SQLContext(sc)
sdf = sqlCtx.createDataFrame(dataset)

我得到了一个错误:

TypeError: Can not merge type <class 'pyspark.sql.types.StringType'> and <class 'pyspark.sql.types.DoubleType'>

共有3个答案

姬银龙
2023-03-14

您需要确保您的熊猫数据帧列适合火花推断的类型。如果您的熊猫数据帧列出了以下内容:

pd.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5062 entries, 0 to 5061
Data columns (total 51 columns):
SomeCol                    5062 non-null object
Col2                       5062 non-null object

你会得到这个错误尝试:

df[['SomeCol', 'Col2']] = df[['SomeCol', 'Col2']].astype(str)

现在,确保。astype(str)实际上是您希望这些列成为的类型。基本上,当底层Java代码试图从python中的对象推断类型时,它会使用一些观察结果并进行猜测,如果该猜测不适用于列中的所有数据,那么它试图从pandas转换为spark,则将失败。

宋昕
2023-03-14

可以通过强制使用如下模式来避免与类型相关的错误:

注意:使用原始数据(如上所述)创建了一个文本文件(test.csv),并插入了假想的列名(“col1”、“col2”、…、“col25”)。

import pyspark
from pyspark.sql import SparkSession
import pandas as pd

spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()

pdDF = pd.read_csv("test.csv")

熊猫数据框架的内容:

       col1     col2    col3    col4    col5    col6    col7    col8   ... 
0      10000001 1       0       1       12:35   OK      10002   1      ...
1      10000001 2       0       1       12:36   OK      10002   1      ...
2      10000002 1       0       4       12:19   PA      10003   1      ...

接下来,创建架构:

from pyspark.sql.types import *

mySchema = StructType([ StructField("col1", LongType(), True)\
                       ,StructField("col2", IntegerType(), True)\
                       ,StructField("col3", IntegerType(), True)\
                       ,StructField("col4", IntegerType(), True)\
                       ,StructField("col5", StringType(), True)\
                       ,StructField("col6", StringType(), True)\
                       ,StructField("col7", IntegerType(), True)\
                       ,StructField("col8", IntegerType(), True)\
                       ,StructField("col9", IntegerType(), True)\
                       ,StructField("col10", IntegerType(), True)\
                       ,StructField("col11", StringType(), True)\
                       ,StructField("col12", StringType(), True)\
                       ,StructField("col13", IntegerType(), True)\
                       ,StructField("col14", IntegerType(), True)\
                       ,StructField("col15", IntegerType(), True)\
                       ,StructField("col16", IntegerType(), True)\
                       ,StructField("col17", IntegerType(), True)\
                       ,StructField("col18", IntegerType(), True)\
                       ,StructField("col19", IntegerType(), True)\
                       ,StructField("col20", IntegerType(), True)\
                       ,StructField("col21", IntegerType(), True)\
                       ,StructField("col22", IntegerType(), True)\
                       ,StructField("col23", IntegerType(), True)\
                       ,StructField("col24", IntegerType(), True)\
                       ,StructField("col25", IntegerType(), True)])

注意:True(表示允许为null)

创建pyspark数据框:

df = spark.createDataFrame(pdDF,schema=mySchema)

确认熊猫数据框现在是pyspark数据框:

type(df)

输出:

pyspark.sql.dataframe.DataFrame

一边:

要解决Kate在下面的评论-要强制实施通用(字符串)模式,可以执行以下操作:

df=spark.createDataFrame(pdDF.astype(str)) 

施敏达
2023-03-14

我制作了这个脚本,它适用于我的10个熊猫数据帧

from pyspark.sql.types import *

# Auxiliar functions
def equivalent_type(f):
    if f == 'datetime64[ns]': return TimestampType()
    elif f == 'int64': return LongType()
    elif f == 'int32': return IntegerType()
    elif f == 'float64': return DoubleType()
    elif f == 'float32': return FloatType()
    else: return StringType()

def define_structure(string, format_type):
    try: typo = equivalent_type(format_type)
    except: typo = StringType()
    return StructField(string, typo)

# Given pandas dataframe, it will return a spark's dataframe.
def pandas_to_spark(pandas_df):
    columns = list(pandas_df.columns)
    types = list(pandas_df.dtypes)
    struct_list = []
    for column, typo in zip(columns, types): 
      struct_list.append(define_structure(column, typo))
    p_schema = StructType(struct_list)
    return sqlContext.createDataFrame(pandas_df, p_schema)

你也可以在这个要点中看到

有了这个,你只需要调用spark_df=pandas_to_spark(pandas_df)

 类似资料:
  • 我有以下两个场景共享的前奏代码: 现在,我想将df转换为pyspark数据帧(

  • 我正在尝试将RDD[String]转换为数据框。字符串是逗号分隔的,所以我希望逗号之间的每个值都有一列。为此,我尝试了以下步骤: 但我明白了: 这不是这篇文章的副本(如何将rdd对象转换为火花中的数据帧),因为我要求RDD[字符串]而不是RDD[行]。 而且它也不是火花加载CSV文件作为DataFrame的副本?因为这个问题不是关于将CSV文件读取为DataFrame。

  • 我有一个如下的CSV文件。 我想把这个转化成下面。 基本上,我想在输出数据帧中创建一个名为idx的新列,该列将填充与键=idx,value=“n”后面的行相同的值“n”。

  • RDD是以数组[数组[字符串]的格式创建的,具有以下值: 我想用模式创建一个数据帧: 接下来的步骤: 给出以下错误:

  • 问题内容: 我正在尝试将Pandas DF转换为Spark one。DF头: 码: 我得到一个错误: 问题答案: 您需要确保您的pandas dataframe列适合spark推断的类型。如果您的熊猫数据框列出类似以下内容: 而且您遇到该错误,请尝试: 现在,确保实际上是您希望这些列成为的类型。基本上,当底层Java代码尝试从python中的对象推断类型时,它会使用一些观察值并做出猜测,如果该猜测

  • 问题内容: 我的问题与此非常相似,但是我需要转换整个数据框,而不仅仅是转换一系列数据框。该功能一次只能在一个系列上使用,不能很好地替代不推荐使用的命令。有没有办法获得与新熊猫版本中的命令相似的结果? 谢谢MikeMüller的示例。如果所有值都可以转换为整数,则效果很好。如果在我的数据帧中我有无法转换为整数的字符串怎么办?例: 然后,我可以运行不赞成使用的函数并获取: 运行命令会给我错误,即使尝试