【问题标题】:Replacing dots with commas on a pyspark dataframe在 pyspark 数据帧上用逗号替换点
【发布时间】:2022-01-24 17:25:06
【问题描述】:

我正在使用下面的代码来收集一些信息:

df = (
  df
  .select(
        date_format(date_trunc('month', col("reference_date")), 'yyyy-MM-dd').alias("month"),
        col("id"),
        col("name"),
        col("item_type"),
        col("sub_group"),
        col("latitude"),
        col("longitude")
  )

我的纬度和经度是带点的值,如下所示:-30.130307 -51.2060018 但我必须将点替换为逗号。我已经尝试了 .replace() 和 .regexp_replace() 但它们都没有工作。请大家帮帮我好吗?

【问题讨论】:

  • “它们都不起作用”,那么会发生什么?
  • 当我像这样使用 .replace() col("longitude").replace('.', ',') 我得到了这个错误SyntaxError: invalid syntax
  • 例如,当我使用df = df.withColumn('new_latitude', regexp_replace('latitude', '.', ',')) 时,我所有的字符都会变成逗号

标签: python dataframe pyspark replace


【解决方案1】:

以以下数据框为例。

df.show()
+-------------------+-------------------+                                       
|           latitude|          longitude|
+-------------------+-------------------+
|  85.70708380916193| -68.05674981929877|
| 57.074495803252404|-42.648691976080215|
|  2.944303748172473| -62.66186439333423|
| 119.76923402031701|-114.41179457810185|
|-138.52573939229234|  54.38429596238362|
+-------------------+-------------------+

您应该可以使用spark.sql 函数,如下所示

from pyspark.sql import functions

df = df.withColumn("longitude", functions.regexp_replace('longitude',r'[.]',","))
df = df.withColumn("latitude", functions.regexp_replace('latitude',r'[.]',","))
df.show()
+-------------------+-------------------+
|           latitude|          longitude|
+-------------------+-------------------+
|  85,70708380916193| -68,05674981929877|
| 57,074495803252404|-42,648691976080215|
|  2,944303748172473| -62,66186439333423|
| 119,76923402031701|-114,41179457810185|
|-138,52573939229234|  54,38429596238362|
+-------------------+-------------------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多