python - 在 DataFrame 中实现自动增量列
问题描述
我正在尝试在 DataFrame 中实现自动增量列。我已经找到了解决方案,但我想知道是否有更好的方法来做到这一点。
我正在使用monotonically_increasing_id()
来自pyspark.sql.functions
. 问题是从 0 开始,我希望它从 1 开始。
所以,我做了以下并且工作正常:
(F.monotonically_increasing_id()+1).alias("songplay_id")
dfLog.join(dfSong, (dfSong.artist_name == dfLog.artist) & (dfSong.title == dfLog.song))\
.select((F.monotonically_increasing_id()+1).alias("songplay_id"), \
dfLog.ts.alias("start_time"), dfLog.userId.alias("user_id"), \
dfLog.level, \
dfSong.song_id, \
dfSong.artist_id, \
dfLog.sessionId.alias("session_id"), \
dfLog.location, \
dfLog.userAgent.alias("user_agent"))
有没有更好的方法来实现我想要做的事情?我认为,仅为此实现 udf 函数的工作量太大,或者只是我?
谢谢。-
解决方案
序列monotonically_increasing_id
不保证是连续的,但保证它们是单调递增的。您工作的每个任务都将被分配一个起始整数,它将在每一行中递增 1,但是您将在一个批次的最后一个 id 和另一个批次的第一个 id 之间存在间隙。要验证此行为,您可以通过重新分区示例数据框来创建包含两个任务的作业:
import pandas as pd
import pyspark.sql.functions as psf
spark.createDataFrame(pd.DataFrame([[i] for i in range(10)], columns=['value'])) \
.repartition(2) \
.withColumn('id', psf.monotonically_increasing_id()) \
.show()
+-----+----------+
|value| id|
+-----+----------+
| 3| 0|
| 0| 1|
| 6| 2|
| 2| 3|
| 4| 4|
| 7|8589934592|
| 5|8589934593|
| 8|8589934594|
| 9|8589934595|
| 1|8589934596|
+-----+----------+
为了确保您的索引产生连续的值,您可以使用窗口函数。
from pyspark.sql import Window
w = Window.orderBy('id')
spark.createDataFrame(pd.DataFrame([[i] for i in range(10)], columns=['value'])) \
.withColumn('id', psf.monotonically_increasing_id()) \
.withColumn('id2', psf.row_number().over(w)) \
.show()
+-----+---+---+
|value| id|id2|
+-----+---+---+
| 0| 0| 1|
| 1| 1| 2|
| 2| 2| 3|
| 3| 3| 4|
| 4| 4| 5|
| 5| 5| 6|
| 6| 6| 7|
| 7| 7| 8|
| 8| 8| 9|
| 9| 9| 10|
+-----+---+---+
笔记:
monotonically_increasing_id
允许您在读取行时设置它们的顺序,它从0
第一个任务开始并增加但不一定以顺序方式row_number
顺序索引有序窗口中的行并开始于1
推荐阅读
- javascript - 尝试为节点替换脚本编写正则表达式
- objective-c - Tableview 在下一次重新加载索引更改时崩溃
- powershell - 在 PowerShell 中复制文件进度
- python - 为什么 TF Boosted Trees 不接受数值数据作为输入?
- angular - 想要监视在 onInit 方法中初始化的方法
- angular - 教程中的 Angular 组件问题
- c# - 如何计算特定块的 AES GCM IV
- node.js - 发送POST请求时Nodejs请求承诺错误?
- variables - 错误:将 varchar 值“...”转换为数据类型 int 时转换失败
- java - 每个扩展类的静态变量