Pyspark:切り上げまたは切り下げの方法(最も近いものに丸める)[複製]
Aug 21 2020
私はこのようなdfを持っています
TEST_schema = StructType([StructField("date", StringType(), True),\
StructField("col1", FloatType(), True),\
])
TEST_data = [('2020-08-01',1.22),('2020-08-02',1.15),('2020-08-03',5.4),('2020-08-04',2.6),('2020-08-05',3.5),\
('2020-08-06',2.2),('2020-08-07',2.7),('2020-08-08',-1.6),('2020-08-09',1.3)]
rdd3 = sc.parallelize(TEST_data)
TEST_df = sqlContext.createDataFrame(TEST_data, TEST_schema)
TEST_df = TEST_df.withColumn("date",to_date("date", 'yyyy-MM-dd'))
TEST_df.show()
+----------+-----+
| date|col1 |
+----------+-----+
|2020-08-01| 1.22|
|2020-08-02| 1.15|
|2020-08-03| 5.4 |
|2020-08-04| 2.6 |
|2020-08-05| 3.5 |
|2020-08-06| 2.2 |
|2020-08-07| 2.7 |
|2020-08-08|-1.6 |
|2020-08-09| 1.3 |
+----------+-----+
ロジック:col1を最も近い値に丸め、整数として返し、max(丸められた値、0)
結果のdfは次のようになります。
+----------+----+----+
| date|col1|want|
+----------+----+----+
|2020-08-01| 1.2| 1|
|2020-08-02| 1.1| 1|
|2020-08-03| 5.4| 5|
|2020-08-04| 2.6| 3|
|2020-08-05| 3.5| 4|
|2020-08-06| 2.2| 2|
|2020-08-07| 2.7| 3|
|2020-08-08|-1.6| 0|
|2020-08-09| 1.3| 1|
+----------+----+----+
回答
Lamanus Aug 22 2020 at 03:07
あなたにすべてを与える重複した質問を確認してください。
data = [('2020-08-01',1.22),('2020-08-02',1.15),('2020-08-03',5.4),('2020-08-04',2.6),('2020-08-05',3.5),('2020-08-06',2.2),('2020-08-07',2.7),('2020-08-08',-1.6),('2020-08-09',1.3)]
df = spark.createDataFrame(data, ['date', 'col1'])
df.withColumn('want', expr('ROUND(col1, 0)').cast('int')).show()
+----------+----+----+
| date|col1|want|
+----------+----+----+
|2020-08-01|1.22| 1|
|2020-08-02|1.15| 1|
|2020-08-03| 5.4| 5|
|2020-08-04| 2.6| 3|
|2020-08-05| 3.5| 4|
|2020-08-06| 2.2| 2|
|2020-08-07| 2.7| 3|
|2020-08-08|-1.6| -2|
|2020-08-09| 1.3| 1|
+----------+----+----+
VITTALB Aug 22 2020 at 07:07
まず、ここでゼロ未満かどうかをチェックしています。ここでは、pyspark関数のwhenメソッドを使用しています。最初に、列の値がゼロ未満であるかどうかを確認します。ゼロ未満の場合は、列の実際の値を取得してから、pyspark.sqlインポートからintにキャストします。 Fとして機能します
TEST_df.withColumn("want", F.bround(F.when(TEST_df["col1"] < 0, 0).otherwise(TEST_df["col1"])).cast("int")).show()
+----------+----+----+
| date|col1|want|
+----------+----+----+
|2020-08-01|1.22| 1|
|2020-08-02|1.15| 1|
|2020-08-03| 5.4| 5|
|2020-08-04| 2.6| 3|
|2020-08-05| 3.5| 4|
|2020-08-06| 2.2| 2|
|2020-08-07| 2.7| 3|
|2020-08-08|-1.6| 0|
|2020-08-09| 1.3| 1|
+----------+----+----+