【问题标题】:select random columns from a very large dataframe in pyspark从pyspark中非常大的数据框中选择随机列
【发布时间】:2017-07-15 04:33:38
【问题描述】:

我在 pyspark 中有一个数据框,它有大约 150 列。这些列是通过连接不同的表获得的。现在我的要求是将数据帧写入文件,但按特定顺序写入,例如先写入 1 到 50 列,然后写入 90 到 110 列,然后再写入第 70 和 72 列。也就是说,我只想选择特定的列并重新排列它们。

我知道其中一种方法是使用 df.select("give your column order") 但在我的情况下,列非常大,不可能在 'select' 中写下每一个列名.

请告诉我如何在 pyspark 中实现这一点。

注意-我无法提供任何示例数据,因为列数非常大,而列号是我的主要障碍。

【问题讨论】:

  • 不知道为什么df.select(list_of_columns) 是个问题
  • Df.select 不是问题,但我想避免在选择中写入超过 100 列。我正在寻找一种可以指定列范围的方法,例如 1-50,55,它会选择 50 列,然后是第 55 列。

标签: python pyspark


【解决方案1】:

听起来您要做的就是以编程方式返回列名列表,从该列表中挑选出一些或多个切片,然后从数据框中按某种顺序选择该列子集。您可以通过操作列表 df.columns 来做到这一点。举个例子:

a=[list(range(10)),list(range(1,11)),list(range(2,12))]
df=sqlContext.createDataFrame(a,schema=['col_'+i for i in 'abcdefghij'])

df 是一个包含['col_a', 'col_b', 'col_c', 'col_d', 'col_e', 'col_f', 'col_g', 'col_h', 'col_i', 'col_j'] 列的数据框。您可以通过调用 df.columns 返回该列表,您可以像对任何其他 python 列表一样对其进行切片和重新排序。您如何做到这一点取决于您以及您要从 df 中选择哪些列以及以何种顺序。例如:

mycolumnlist=df.columns[8:9]+df.columns[0:5]
df[mycolumnlist].show()

返回

+-----+-----+-----+-----+-----+-----+
|col_i|col_a|col_b|col_c|col_d|col_e|
+-----+-----+-----+-----+-----+-----+
|    8|    0|    1|    2|    3|    4|
|    9|    1|    2|    3|    4|    5|
|   10|    2|    3|    4|    5|    6|
+-----+-----+-----+-----+-----+-----+

【讨论】:

    【解决方案2】:

    您可以通过编程方式创建列列表

    first_df.join(second_df, on-'your_condition').select([column_name for column_name in first_df.columns] + [column_name for column_name in second_df.columns])
    

    您可以使用random.sample(first_df.columns, number_of_columns) 函数选择随机的列子集。

    希望这会有所帮助:)

    【讨论】:

    • 这将随机选择列而不是我想要的。
    • 如果您知道要选择 哪些 列,则可以使用类似 [column_name for column_name in first_df.columns if column_name in column_subset] 的内容,其中 column_subset 是您要选择的列的列表。如果两个数据集包含相同的列,这可能会失败。
    猜你喜欢
    • 2020-02-19
    • 2022-01-09
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 2019-12-09
    • 2018-03-30
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多