gpt4 book ai didi

python - 如何将 pyspark 数据帧分成两行

转载 作者:太空狗 更新时间:2023-10-29 20:40:16 25 4
gpt4 key购买 nike

我在 Databricks 工作。

我有一个包含 500 行的数据框,我想创建两个包含 100 行的数据框,另一个包含剩余的 400 行。

+--------------------+----------+
| userid| eventdate|
+--------------------+----------+
|00518b128fc9459d9...|2017-10-09|
|00976c0b7f2c4c2ca...|2017-12-16|
|00a60fb81aa74f35a...|2017-12-04|
|00f9f7234e2c4bf78...|2017-05-09|
|0146fe6ad7a243c3b...|2017-11-21|
|016567f169c145ddb...|2017-10-16|
|01ccd278777946cb8...|2017-07-05|

我已经尝试了下面的但是我收到了一个错误

df1 = df[:99]
df2 = df[100:499]


TypeError: unexpected item type: <type 'slice'>

最佳答案

最初我误会了,以为你想对列进行切片。如果要选择行的子集,一种方法是使用 monotonically_increasing_id() 创建索引列.来自文档:

The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive.

您可以使用此 ID 对数据帧进行排序,并使用 limit() 对其进行子集化,以确保您准确获得所需的行。

例如:

import pyspark.sql.functions as f
import string

# create a dummy df with 500 rows and 2 columns
N = 500
numbers = [i%26 for i in range(N)]
letters = [string.ascii_uppercase[n] for n in numbers]

df = sqlCtx.createDataFrame(
zip(numbers, letters),
('numbers', 'letters')
)

# add an index column
df = df.withColumn('index', f.monotonically_increasing_id())

# sort ascending and take first 100 rows for df1
df1 = df.sort('index').limit(100)

# sort descending and take 400 rows for df2
df2 = df.sort('index', ascending=False).limit(400)

只是为了验证这做了你想要的:

df1.count()
#100
df2.count()
#400

我们还可以验证索引列不重叠:

df1.select(f.min('index').alias('min'), f.max('index').alias('max')).show()
#+---+---+
#|min|max|
#+---+---+
#| 0| 99|
#+---+---+

df2.select(f.min('index').alias('min'), f.max('index').alias('max')).show()
#+---+----------+
#|min| max|
#+---+----------+
#|100|8589934841|
#+---+----------+

关于python - 如何将 pyspark 数据帧分成两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com