如何用不相等的列表平面映射数据帧?

2024-04-20 09:08:50 发布

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

我有一个数据帧如下-

  a  |       b       |   c      
 [1] |    [3,4,5,6] | [7,8,9,10]

我需要输出为

^{pr2}$

目前,我使用以下语句得到如下输出-

cols=['a','b','c']
df.rdd.flatMap(lambda x: itertools.izip_longest(*[x[c] for c in cols])).toDF(cols)

  a  |   b       |   c
  1      3           7
 null    4           8
 null    5           9
 null    6           10 

列数不是固定的。如果解是广义的,那将是有帮助的。在


Tags: 数据lambdaindfforlongest语句null
1条回答
网友
1楼 · 发布于 2024-04-20 09:08:50

在 一种选择是使用itertools.repeat来重复长度小于最长数组长度的每个数组。在

from itertools import izip_longest, repeat, chain

cols = df.columns
def zip_with_repeat(row, cols):
    M = max(len(row[c]) for c in cols)
    return izip_longest(
        *[list(chain(*repeat(row[c], (M - len(row[c])) + 1)))[:M] for c in cols]
    )

df.rdd.flatMap(lambda row: zip_with_repeat(row, cols)).toDF(cols).show()
#+ -+ -+ -+
#|  a|  b|  c|
#+ -+ -+ -+
#|  1|  3|  7|
#|  1|  4|  8|
#|  1|  5|  9|
#|  1|  6| 10|
#+ -+ -+ -+

为了便于说明,假设您使用以下数据帧:

^{pr2}$

该准则将产生:

^{3}$

请注意,10重复了一次,以将第a列中的数组填充到适当的长度。在

相关问题 更多 >