【问题标题】:Transpose a dataframe in Pyspark在 Pyspark 中转置数据帧
【发布时间】:2018-11-23 21:28:03
【问题描述】:

如何在 Pyspark 中转置以下数据框?

这个想法是实现下面出现的结果。

import pandas as pd

d = {'id' : pd.Series([1, 1, 1, 2, 2, 2, 3, 3, 3], index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']),
     'place' : pd.Series(['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']),
     'value' : pd.Series([10, 30, 20, 10, 30, 20, 10, 30, 20], index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']),
     'attribute' : pd.Series(['size', 'height', 'weigth', 'size', 'height', 'weigth','size', 'height', 'weigth'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'])}

   id place  value attribute
a   1     A     10      size
b   1     A     30    height
c   1     A     20    weigth
d   2     A     10      size
e   2     A     30    height
f   2     A     20    weigth
g   3     A     10      size
h   3     A     30    height
i   3     A     20    weigth

d = {'id' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
     'place' : pd.Series(['A', 'A', 'A'], index=['a', 'b', 'c']),
     'size' : pd.Series([10, 30, 20], index=['a', 'b', 'c']),
     'height' : pd.Series([10, 30, 20], index=['a', 'b', 'c']),
     'weigth' : pd.Series([10, 30, 20], index=['a', 'b', 'c'])}

df = pd.DataFrame(d)
print(df)

   id place  size  height  weigth
a   1     A    10      10      10
b   2     A    30      30      30
c   3     A    20      20      20

欢迎任何帮助。从已经非常感谢你了

【问题讨论】:

标签: apache-spark pyspark apache-spark-sql


【解决方案1】:

首先,我认为您的示例输出不正确。您的输入数据的大小设置为 10,高度设置为 30,重量设置为每个 id 的 20,但是对于 id 1,所需的输出设置为 10。如果这真的是您的情况,请再解释一下。如果这是一个错误,那么您想使用pivot 函数。示例:

from pyspark.sql.functions import first
l =[( 1        ,'A', 10, 'size' ),
( 1        , 'A', 30, 'height' ),
( 1        , 'A', 20, 'weigth' ),
( 2        , 'A', 10, 'size' ),
( 2        , 'A', 30, 'height' ),
( 2        , 'A', 20, 'weigth' ),
( 3        , 'A', 10, 'size' ),
( 3        , 'A', 30, 'height' ),
( 3        , 'A', 20, 'weigth' )]

df = spark.createDataFrame(l, ['id','place', 'value', 'attribute'])

df.groupBy(df.id, df.place).pivot('attribute').agg(first("value")).show()

+---+-----+------+----+------+ 
| id|place|height|size|weigth|
+---+-----+------+----+------+ 
|  2|    A|    30|  10|    20| 
|  3|    A|    30|  10|    20| 
|  1|    A|    30|  10|    20|
+---+-----+------+----+------+

【讨论】:

  • 谢谢!这就是我要找的东西!
  • 有没有办法将空值替换为 0?我的输出有空值
  • 当然fillna
【解决方案2】:

请参阅documentationPivoting 总是在聚合上下文中完成,我在这里选择了sum。因此,如果对于相同的 idplaceattribute,有多个值,则取它们的总和。您也可以使用最小值、最大值或平均值,具体取决于您的需要。

df = df.groupBy(["id","place"]).pivot("attribute").sum("value")

这个link 也解决了同样的问题。

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 2018-03-09
    • 2021-05-21
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多