【发布时间】:2020-07-10 16:12:42
【问题描述】:
继续问题:pyspark dataframe withColumn command not working
我有一个输入数据框:df_input(更新的 df_input)
|comment|inp_col|inp_val|
|11 |a |a1 |
|12 |a |a2 |
|12 |f |&a |
|12 |a |f9 |
|15 |b |b3 |
|16 |b |b4 |
|17 |c |&b |
|17 |c |c5 |
|17 |d |&c |
|17 |d |d6 |
|17 |e |&d |
|17 |e |e7 |
如果您看到 inp_col 和 inp_val 具有层次结构,并且它可以是具有根值的 n 数。这里的父值是 "b" 和 "a"。
现在,根据我的要求,我必须将以 "&" 开头的子值替换为其对应的值。 我尝试迭代以 inp_val 列中的“&”值开头的值列表,并在每次迭代中用值列表替换。 但是,它没有奏效。我面临如何获取包含父子列表值的列表的问题。
试过的代码:
list_1 = [row['inp_val'] for row in tst.select(tst.inp_val).where(tst.inp_val.substr(0, 1) == '&').collect()]
# removing the '&' at every starting of the list values
list_2 = [list_val[1:] for list_val in list_1]
tst_1 = tst.withColumn("val_extract", when(tst.inp_val.substr(0, 1) == '&', regexp(tst.inp_val, "&", "")).otherwise(tst.inp_val))
for val in list_2:
df_leaf = tst_1.select(tst_1.val_extract).where(tst_1.inp_col == val)
list_3 = [row['val_extract'] for row in df_leaf.collect()]
tst_1 = tst_1.withColumn('bool', when(tst_1.val_extract == val, 'True').otherwise('False'))
tst_1 = tst_1.withColumn('val_extract', when(tst_1.bool == 'True', str(list_3)).otherwise(tst_1.val_extract)).drop('bool')
更新的预期输出:
|comment|inp_col|inp_val|inp_extract |
|11 |a |a1 |['a1'] |
|12 |a |a2 |['a2'] |
|12 |f |&a |['a1, 'a2'] |
|12 |f |f9 |['f9'] |
|15 |b |b3 |['b3'] |
|16 |b |b4 |['b4'] |
|17 |c |&b |['b3', 'b4'] |
|18 |c |c5 |['c5'] |
|19 |d |&c |['b3', 'b4', 'c5'] |
|20 |d |d6 |['d6'] |
|21 |e |&d |['b3', 'b4', 'c5', 'd6'] |
|22 |e |e7 |['e7'] |
之后我可以尝试做爆炸来获得多行。但是,aove 输出是我们需要的,无法得到一定的百分比结果。
【问题讨论】:
-
您的案例似乎比仅 1 个自联接更复杂(与上一个问题相比),它可能需要 n 次自联接,具体取决于数据的复杂性。 spark graphframes r 是通往这里的道路,因为它们是真正为 spark 数据帧上的图形操作而构建的
https://docs.databricks.com/spark/latest/graph-analysis/graphframes/user-guide-python.html
标签: python pyspark hierarchical-data pyspark-dataframes tarjans-algorithm