在pyspark中使用exec()为数据帧创建列不起作用

2024-09-28 21:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含多个列的dataframe,我创建了一个代码片段来生成一个新的列“label”,它表示一个包含其余列信息的字符串。在

假设我有下一个数据帧'df':

+------------+------+
| Atr0       | Atr1 |
+------------+------+
|     0      |  1   |
+------------+------+
|     0      |  2   |
+------------+------+
|     0      |  8   |
+------------+------+
|     ...    |  ... |
+------------+------+

因此,我想创建一个新的数据帧“df”,它是:

^{pr2}$

如果我执行下一个代码片段,它会起作用:

df = df.withColumn('Atr2', concat(lit("Atr0="), col('Atr0'), lit(", Atr1="), col('Atr1'))

但我希望代码不依赖于用户。我的意思是,我有一个包含dataframe列的变量'list',所以我想迭代这个列表,以便自动生成新的列。这里是我生成的代码:

def addColumn(list):

    # Many operations to create the dataframe 'df'
    list = list + ['AtrX']
    # list is a variable containing ['Atr0', 'Atr1', 'AtrX']
    label = "df = df.withColumn('label', concat("

    count_aux = 0
    for atributo_aux in list:
        if(count_aux == 0):
            label = label + "lit('" + atributo_aux + "='), col('" + atributo_aux + "')" 
        else:
            label = label + ", lit('," + atributo_aux + "='), col('" + atributo_aux + "')"
        count_aux += 1

    label = label + "))" 
    print(label)
    exec(label)

但是当我执行函数时,数据帧永远不会更新。我检查了字符串是否正确生成,它是正确的。为什么如果我执行代码时手动输入列名,它会被完美地更新,而在上面生成的代码中却没有呢?在


Tags: 数据字符串代码dataframedfcountcollabel