如何创建新列以根据具有 NULL 值的另一列的不同组合对产品进行分类

问题描述 投票:0回答:0

我有一个存储产品的 MySQL 5.7 表。节点列指的是类别和子类别。在这些节点中,只有node_0和node_4保证为非NULL,而其他节点可能为NULL,也可能不为NULL。该表将用于根据节点值的唯一组合(unique_cat)批量处理产品。每个独特的组合可以有 1 到 50 种产品。各个节点名称不是唯一的(即,node_i 可以与 node_k 具有相同的名称),但这些节点的组合是唯一的。

一个可重现的示例如下:

    CREATE TABLE products (
    product_id int(11) NOT NULL AUTO_INCREMENT,
    node_0 varchar(400) DEFAULT NULL,
    node_1 varchar(400) DEFAULT NULL,
    node_2 varchar(400) DEFAULT NULL,
    node_3 varchar(400) DEFAULT NULL,
    node_4 varchar(255) DEFAULT NULL,
    PRIMARY KEY (id)
);

INSERT INTO products (node_0, node_1, node_2, node_3, node_4) VALUES
('a_0', NULL, NULL, NULL, 'a_1'),
('a_0', NULL, NULL, NULL, 'a_1'),
('a_2', 'a_1', NULL, NULL, 'a_1'),
('a_0', NULL, NULL, 'a_3', 'a_2'),
('a_3', NULL, NULL, 'a_0', 'a_2'),
('a_0', NULL, NULL, NULL, 'a_2'),
('a_2', 'a_1', NULL, NULL, 'a_1')

我需要创建一个新列 unique_cat,它是一个数字,表示节点_0、节点_1、节点_2、节点_3 和节点_4 组合的不同值。我不确定如何在这种情况下处理 NULL 值。 预期输出:

| node_0 | node_1 | node_2 | node_3 | node_4 | unique_cat |
|--------|--------|--------|--------|--------|------------|
| a_0    | NULL   | NULL   | NULL   | a_1    | 0          |
| a_0    | NULL   | NULL   | NULL   | a_1    | 0          |
| a_2    | a_1    | NULL   | NULL   | a_1    | 1          |
| a_0    | NULL   | NULL   | a_3    | a_2    | 2          |
| a_3    | NULL   | NULL   | a_0    | a_2    | 3          |
| a_0    | NULL   | NULL   | NULL   | a_2    | 4          |
| a_2    | a_1    | NULL   | NULL   | a_1    | 1          |

仅处理node_0和node_4时,以下方法有效:

# Create a unique combination of node_0,node_4 with unique IDs
unique_cat_df = df \
      .select("node_0", "node_4") \
      .distinct() \
      .withColumn("unique_cat", monotonically_increasing_id())

# Join the unique combinations back to the original DataFrame
df_with_cat_ids = df.join(
      unique_cat_df,
      on=["node_0", "node_4"],
      how="left"
)

但是,当我尝试包含可以为 NULL 的节点时,它无法按预期工作。这是我尝试过的:

placeholder = "___NULL___"
df = df_0 \
    .withColumn("node_2", F.when(col("node_2").isNull(), placeholder).otherwise(col("node_2"))) \
    .withColumn("node_3", F.when(col("node_3").isNull(), placeholder).otherwise(col("node_3")))

# Select columns and create distinct combinations with a unique ID
unique_combinations_df = df \
    .select("node_0", "node_1", "node_2", "node_3", "node_4") \
    .distinct() \
    .withColumn("unique_cat", monotonically_increasing_id())

# Join the unique combinations back to the original DataFrame
df_with_ids = lastest_data_df_2.join(
    unique_combinations_df,
    on=["current_node", "node_1", "node_2", "node_3", "root_node"],
    how="left"
)

这个方法行不通。有什么想法或建议吗?谢谢!

更新:解决了!

经过大量的绞尽脑汁、喝咖啡休息和思考生命的意义之后,我发现了我的代码无法按预期工作的罪魁祸首:

🥁鼓声🥁

我忘记替换node_1中的NULL值! 🚨

我感到羞耻...🙂

mysql pyspark
© www.soinside.com 2019 - 2024. All rights reserved.