繁体   English   中英

如何将数据从大熊猫数据帧加载到Spark数据帧

[英]How to load data in chunks from a pandas dataframe to a spark dataframe

我已经通过像这样的pyodbc连接读取了大块数据:

import pandas as pd
import pyodbc
conn = pyodbc.connect("Some connection Details")
sql = "SELECT * from TABLES;"
df1 = pd.read_sql(sql,conn,chunksize=10)

现在,我想使用以下方法将所有这些块读取到一个单一的火花数据帧中:

i = 0
for chunk in df1:
    if i==0:
        df2 = sqlContext.createDataFrame(chunk)
    else:
        df2.unionAll(sqlContext.createDataFrame(chunk))
    i = i+1

问题是当我执行df2.count()我得到的结果为10,这意味着只有i = 0的情况有效,这是unionAll的错误。 我在这里做错什么了吗?

.unionAll()的文档指出,它返回一个新的数据.unionAll() ,因此您必须将其分配回df2框:

i = 0
for chunk in df1:
    if i==0:
        df2 = sqlContext.createDataFrame(chunk)
    else:
        df2 = df2.unionAll(sqlContext.createDataFrame(chunk))
    i = i+1

此外,您可以改为使用enumerate()避免自己管理i变量:

for i,chunk in enumerate(df1):
    if i == 0:
        df2 = sqlContext.createDataFrame(chunk)
    else:
        df2 = df2.unionAll(sqlContext.createDataFrame(chunk))

此外, .unionAll()的文档指出已弃用.unionAll() ,现在您应该使用.union() ,其行为类似于SQL中的UNION ALL:

for i,chunk in enumerate(df1):
    if i == 0:
        df2 = sqlContext.createDataFrame(chunk)
    else:
        df2 = df2.union(sqlContext.createDataFrame(chunk))

编辑:
此外,我将不再继续说,但在我进一步说之前,不要再说了:正如@ zero323所说的,我们不要在循环中使用.union() 让我们做一些类似的事情:

def unionAll(*dfs):
    ' by @zero323 from here: http://stackoverflow.com/a/33744540/42346 '
    first, *rest = dfs  # Python 3.x, for 2.x you'll have to unpack manually
    return first.sql_ctx.createDataFrame(
        first.sql_ctx._sc.union([df.rdd for df in dfs]),
        first.schema
    )

df_list = []
for chunk in df1:
    df_list.append(sqlContext.createDataFrame(chunk))

df_all = unionAll(df_list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM