例如,我有一个数据集

Column A Column B Column C Column D
Cell A1 Cell B1 Cell C1 Cell D1
Cell A2 Cell B2 Cell C2 Cell D2
Cell A3 Cell B3 Cell C3 Cell D3
Cell A4 Cell B4 Cell C4 Cell D4

有没有可能我可以把n行连接在一起.例如,第1行和第2行连接在一起,同时维护列? 所以,我可以

Column A Column B Column C Column D
Cell A1, A2 Cell B1, B2 Cell C1, C2 Cell D1, D2
Cell A3, A4 Cell B3, B4 Cell C3, C4 Cell D3, D4

推荐答案

你可以试一下row_number(), monotonically_increasing_id().

通过在row_number字段上获得%来创建组,然后使用sum窗口操作来获得组.

100

from pyspark.sql import *
from pyspark.sql.functions import *
window = Window.partitionBy(lit(1)).orderBy('Column A')
window_mid = Window.partitionBy(lit(1)).orderBy('mid')

df.withColumn("rn", row_number().over(window)).\
  withColumn("grp", (col("rn")%2)).\
    withColumn("mid", monotonically_increasing_id()).\
    withColumn("sum", sum(col("grp")).over(window_mid)).\
        groupBy("sum").agg(array_join(collect_list(col("Column A")),',').alias("column a"),
                           array_join(collect_list(col("Column B")),',').alias("column b"),
                           array_join(collect_list(col("Column C")),',').alias("column c"),
                           array_join(collect_list(col("Column D")),',').alias("column d")).\
          drop(*['rn','grp','mid','sum']).show()

#+---------------+---------------+---------------+---------------+
#|       column a|       column b|       column c|       column d|
#+---------------+---------------+---------------+---------------+
#|Cell A1,Cell A2|Cell B1,Cell B2|Cell C1,Cell C2|Cell D1,Cell D2|
#|Cell A3,Cell A4|Cell B3,Cell B4|Cell C3,Cell C4|Cell D3,Cell D4|
#+---------------+---------------+---------------+---------------+

Python相关问答推荐

如何使用scipy从频谱图中回归多个高斯峰?

Python会扔掉未使用的表情吗?

Python在tuple上操作不会通过整个单词匹配

当使用keras.utils.Image_dataset_from_directory仅加载测试数据集时,结果不同

scikit-learn导入无法导入名称METRIC_MAPPING64'

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

从dict的列中分钟

为什么sys.exit()不能与subproccess.run()或subprocess.call()一起使用

在Mac上安装ipython

如何获得每个组的时间戳差异?

使用NeuralProphet绘制置信区间时出错

启用/禁用shiny 的自动重新加载

python panda ExcelWriter切换动态公式到数组公式

OpenCV轮廓.很难找到给定图像的所需轮廓

递归函数修饰器

使用类型提示进行类型转换

Python将一个列值分割成多个列,并保持其余列相同

python的文件. truncate()意外地没有截断'

合并相似列表

查找数据帧的给定列中是否存在特定值