PySpark 如何将 CSV 读入 Dataframe 并对其进行操作

PySpark How to read CSV into Dataframe, and manipulate it

我对 pyspark 很陌生,正在尝试使用它来处理保存为 csv 文件的大型数据集。 我想将 CSV 文件读入 spark 数据框,删除一些列,然后添加新列。 我应该怎么做?

我无法将此数据放入数据框中。这是我目前拥有的精简版:

def make_dataframe(data_portion, schema, sql):
    fields = data_portion.split(",")
    return sql.createDateFrame([(fields[0], fields[1])], schema=schema)

if __name__ == "__main__":
    sc = SparkContext(appName="Test")
    sql = SQLContext(sc)

    ...

    big_frame = data.flatMap(lambda line: make_dataframe(line, schema, sql))
                .reduce(lambda a, b: a.union(b))

    big_frame.write \
        .format("com.databricks.spark.redshift") \
        .option("url", "jdbc:redshift://<...>") \
        .option("dbtable", "my_table_copy") \
        .option("tempdir", "s3n://path/for/temp/data") \
        .mode("append") \
        .save()

    sc.stop()

这会在缩减步骤中产生错误 TypeError: 'JavaPackage' object is not callable

这可以吗?减少到数据帧的想法是能够将结果数据写入数据库(Redshift,使用 spark-redshift 包)。

我也尝试过将 unionAll()map()partial() 一起使用,但无法正常工作。

我是运行亚马逊的EMR,spark-redshift_2.10:2.0.0和亚马逊的JDBCdriverRedshiftJDBC41-1.1.17.1017.jar.

更新 - 也在评论中回答你的问题:

从 CSV 读取数据到数据框: 您似乎只尝试将 CSV 文件读入 spark 数据帧。

如果是这样 - 我的回答是: 覆盖这个。

以下代码应将 CSV 读入 spark-data-frame

import pyspark
sc = pyspark.SparkContext()
sql = SQLContext(sc)

df = (sql.read
         .format("com.databricks.spark.csv")
         .option("header", "true")
         .load("/path/to_csv.csv"))

// these lines are equivalent in Spark 2.0 - using [SparkSession][1]
from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

spark.read.format("csv").option("header", "true").load("/path/to_csv.csv") 
spark.read.option("header", "true").csv("/path/to_csv.csv")

删除列

您可以使用 "drop(col)" 删除列 https://spark.apache.org/docs/1.6.2/api/python/pyspark.sql.html

下降(列)

Returns a new DataFrame that drops the specified column.
Parameters: col – a string name of the column to drop, or a Column to drop.

>>> df.drop('age').collect()
[Row(name=u'Alice'), Row(name=u'Bob')]

>>> df.drop(df.age).collect()
[Row(name=u'Alice'), Row(name=u'Bob')]

>>> df.join(df2, df.name == df2.name, 'inner').drop(df.name).collect()
[Row(age=5, height=85, name=u'Bob')]

>>> df.join(df2, df.name == df2.name, 'inner').drop(df2.name).collect()
[Row(age=5, name=u'Bob', height=85)]

添加列 您可以使用 "withColumn" https://spark.apache.org/docs/1.6.2/api/python/pyspark.sql.html

withColumn(colName, col)

Returns a new DataFrame by adding a column or replacing the existing column that has the same name.
Parameters: 

    colName – string, name of the new column.
    col – a Column expression for the new column.

>>> df.withColumn('age2', df.age + 2).collect()
[Row(age=2, name=u'Alice', age2=4), Row(age=5, name=u'Bob', age2=7)]

注意:spark还有很多其他的函数可以使用(比如你可以用"select"代替"drop")