【问题标题】:How to move a specific column of a pyspark dataframe in the start of the dataframe如何在数据框的开头移动 pyspark 数据框的特定列
【发布时间】:2019-11-29 13:53:47
【问题描述】:

我有一个 pyspark 数据框如下(这只是一个简化的示例,我的实际数据框有数百列):

col1,col2,......,col_with_fix_header
1,2,.......,3
4,5,.......,6
2,3,........,4

我想在开始时移动 col_with_fix_header,以便输出如下:

col_with_fix_header,col1,col2,............
3,1,2,..........
6,4,5,....
4,2,3,.......

我不想列出解决方案中的所有列。

【问题讨论】:

  • 但我不想列出所有列名。在此示例中,有三列,但在我的实际情况中,有 1O0 列,我只想获取具有固定标题的最后一列并将其移动到开头

标签: pyspark pyspark-dataframes


【解决方案1】:

如果您不想列出数据框的所有列,可以使用数据框属性columns。此属性为您提供了一个 Python 列名列表,您可以简单地对其进行切片:

df = spark.createDataFrame([
  ("a", "Alice", 34),
  ("b", "Bob", 36),
  ("c", "Charlie", 30),
  ("d", "David", 29),
  ("e", "Esther", 32),
  ("f", "Fanny", 36),
  ("g", "Gabby", 60)], ["id", "name", "age"])
  
df.select([df.columns[-1]] + df.columns[:-1]).show()

输出:

+---+---+-------+
|age| id|   name|
+---+---+-------+
| 34|  a|  Alice|
| 36|  b|    Bob|
| 30|  c|Charlie|
| 29|  d|  David|
| 32|  e| Esther|
| 36|  f|  Fanny|
| 60|  g|  Gabby|
+---+---+-------+

【讨论】:

猜你喜欢
  • 2020-07-07
  • 2022-01-26
  • 1970-01-01
  • 2017-12-17
  • 2022-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多