我是Pyspark的新手,我希望对此有所帮助。我有一个Pyspark数据框df1
,如下所示:
df1 =
|---------------------|------------------|------------------|
| ID_Machine | Event_Duration | Timestamp |
|---------------------|------------------|------------------|
| 1 | 34 | 213 |
|---------------------|------------------|------------------|
| 1 | 97 | 572 |
|---------------------|------------------|------------------|
| 1 | 78 | 872 |
|---------------------|------------------|------------------|
| 2 | 83 | 345 |
|---------------------|------------------|------------------|
| 2 | 14 | 718 |
|---------------------|------------------|------------------|
| 2 | 115 | 884 |
|---------------------|------------------|------------------|
通过它,我必须使用聚合方法执行groupBy
:
df2 = df1.groupBy("ID_Machine").agg(F.max("Event_duration").alias("Max_Event_Duration")
因此获得:
df2 =
|---------------------|---------------------------|
| ID_Machine | Max_Event_Duration |
|---------------------|---------------------------|
| 1 | 97 |
|---------------------|---------------------------|
| 2 | 115 |
|---------------------|---------------------------|
到目前为止,太好了。但是,现在我想在Excel中执行某种功能,例如vlookup
,在其中我检索Timestamp
中的df1
值,该值对应于{{1}中的Max_Event_Duration
},获得以下内容:
df2
有人知道如何创建此第三个数据帧或如何修改创建|---------------------|---------------------|------------------|
| ID_Machine | Max_Event_Duration | Timestamp |
|---------------------|---------------------|------------------|
| 1 | 97 | 572 |
|---------------------|---------------------|------------------|
| 2 | 115 | 884 |
|---------------------|---------------------|------------------|
的代码以包括各自的df2
值吗?
谢谢!
答案 0 :(得分:1)
您可以创建一个max_event_duration
的新列,并过滤event_duration = max_event_duration
df2 = df1.select('*', F.max("Event_duration").over(Window.partitionBy("ID_Machine")).alias("Max_Event_Duration")) \
.filter("Event_duration = Max_Event_Duration") \
.drop("Max_Event_Duration")
答案 1 :(得分:1)
首先必须创建一个数据事件,该事件的最大事件与OG数据帧中的事件相同。
df_max = df1.groupBy("ID_Machine").agg(F.max("Event_Duration").alias("Event_Duration"))
df_max.show()
哪一个能给你df
+----------+--------------+
|ID_Machine|Event_Duration|
+----------+--------------+
| 1| 97|
| 2| 115|
+----------+--------------+
然后通过两个相似的命名列将数据框连接起来,然后重命名事件持续时间
df_combined = df_max.join(df1, ["ID_Machine", "Event_Duration"]) \
.withColumnRenamed("Event_Duration", "Max_Event_Duration")
df_combined.show()
这会给你
+----------+------------------+---------+
|ID_Machine|Max_Event_Duration|Timestamp|
+----------+------------------+---------+
| 2| 115| 884|
| 1| 97| 572|
+----------+------------------+---------+