Skip to main content
 首页 » 编程设计

python之为 PySpark dataFrame 中的特定单元格赋值

2025年05月04日28yyy_WW

我想使用 PySpark 更改我的 Spark DataFrame 的特定单元格中的值。

简单示例 - 我创建了一个模拟 Spark DataFrame:

df = spark.createDataFrame( 
    [ 
     (1, 1.87, 'new_york'),  
     (4, 2.76, 'la'),  
     (6, 3.3, 'boston'),  
     (8, 4.1, 'detroit'),  
     (2, 5.70, 'miami'),  
     (3, 6.320, 'atlanta'),  
     (1, 6.1, 'houston') 
    ], 
    ('variable_1', "variable_2", "variable_3") 
) 

运行 display(df) 我得到这张表:

variable_1   variable_2   variable_3 
    1           1.87    new_york 
    4           2.76    la 
    6           3.3     boston 
    8           4.1     detroit 
    2           5.7     miami 
    3           6.32    atlanta 
    1           6.1     houston 

例如,我想为第 4 行第 3 列的单元格分配一个新值,即将 detroit 更改为 new_orleans。我知道 df.iloc[4, 3] = 'new_orleans' 或 df.loc[4, 'detroit'] = 'new_orleans' 在 Spark 。

使用 when 对我的问题的有效答案是:

from pyspark.sql.functions import when 
targetDf = df.withColumn("variable_3", \ 
              when(((df["variable_1"] == 8) & (df["variable_2"] == 4.1)) , 'new_orleans').otherwise(df["variable_3"])) 

我的问题是:这是否可以在 PySpark 中以更实用的方式完成,而无需输入我只想更改 1 个单元格的行的所有值和列名(也许在不使用 when 函数的情况下实现相同的效果)?

预先感谢您的帮助和@useruser9806664 的反馈。

请您参考如下方法:

Spark DataFrames 是不可变的,不提供随机访问,严格来说,无序。结果:

  • 您不能分配任何东西(因为不可变属性)。
  • 您不能访问特定行(因为没有随机访问)。
  • “indcies”行未明确定义(因为未排序)。

您可以做的是用新列创建一个新的数据框,替换现有的,使用一些条件表达式,这已经包含在您找到的答案中。

此外,monotonically_increasing_id 不添加索引(行号)。它添加单调递增的数字,不一定是连续的数字或从任何特定值开始(在空分区的情况下)。