开发者社区> 问答> 正文

在Pyspark中转置数据框

如何在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

展开
收起
社区小助手 2018-12-10 16:39:25 2027 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    首先,我认为您的样本输出不正确。对于每个id,您的输入数据的大小设置为10,高度设置为30,权重设置为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|

    2019-07-17 23:19:25
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Adopting Dataframes and Parque 立即下载
Data Wrangling with PySpark for Data Scientists Who Know Pandas 立即下载
LEARNINGS USING SPARK STREAMING & DATAFRAMES FOR WALMART SEARCH 立即下载