python - 函数不返回 pyspark DataFrame

标签 python function dataframe pyspark

我定义了一个函数,它返回作为输入给出的所有数据帧的交集的数据帧。但是,当我将函数的输出存储在某个变量中时,它不会存储在该变量中。它显示为一个非类型对象

def intersection(list1, intersection_df,i):
    if (i == 1):
        intersection_df = list1[0]
        print(type(intersection_df))
        intersection(list1, intersection_df, i+1)
    elif (i>len(list1)):
        print(type(intersection_df))
        a = spark.createDataFrame(intersection_df.rdd)
        a.show()
        return a
    else:
        intersection_df = intersection_df.alias('intersection_df')
        tb = list1[i-1]
        tb = tb.alias('tb')
        intersection_df = intersection_df.join(tb, intersection_df['value'] == tb['value']).where(col('tb.value').isNotNull()).select(['intersection_df.value'])
        print(type(intersection_df))
        intersection(list1, intersection_df, i+1)

例如,如果我输入如下,

list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
list2 = [3,4,5,6,7,8,9,10,11,12,13,14,15,16]
list3 = [6,7,8,9,10,11,12,13,4,16,343]
df1 = spark.createDataFrame(list1, StringType())
df2 = spark.createDataFrame(list2, StringType())
df3 = spark.createDataFrame(list3, StringType())
list4 = [df1,df2,df3]
empty_df = []
intersection_df = intersection(list4, empty_df, 1)

我希望以下输出存储在 interesection_df 中

 +-----+
 |value|
 +-----+
 | 7   |
 | 11  |
 | 8   |
 | 6   |
 | 9   |
 | 10  |
 | 4   |
 | 12  |
 | 13  |
 +-----+

最佳答案

我认为你受到了递归诅咒的打击。

问题:
您正在递归调用 intersection 但仅在其中一个 if 条件下返回。因此,当它返回 df 时,它无处可去(回想一下:每个函数调用都会创建一个堆栈)。

解决方案:
当您从 ifelse 条件调用 intersection 时返回。例如 if 条件中的 return junction(list1, junction_df, i+1)

关于python - 函数不返回 pyspark DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56389822/

相关文章:

python - 如何合并具有来自多列的重复值的行

python-3.x - 将列表列表转换为字符串 pandas 数据框

python - Tensorflow ValueError : All shapes must be fully defined: [TensorShape([Dimension(None), 维度(无),维度(3)]),TensorShape([])

python - 屏蔽python 2d数组以在特定阈值下更改圆圈中的值

python - 使用元类时出现 Pylint 错误

javascript - 在 Javascript 中执行作为参数传递的函数?

python - 带有 UnboundLocalError 的本地和全局引用

javascript - 从 AngularJS 调用外部函数

r - 连接列并将它们添加到数据框的开头

python - Pandas - 根据唯一值和不同的列日期时间过滤 DataFrame