首页 > 编程问答 >PySpark 逆透视或减少

PySpark 逆透视或减少

时间:2024-07-23 14:03:31浏览次数:8  
标签:python pyspark

我有以下数据框:

df = spark.createDataFrame(
    [
        ("D1", "D2", "H1", None, None),
        ("D1", "D2", "H1", "H2", None),
        ("D1", "D2", "H1", "H2", "H3")
    ],
    ["Dimension1", "Dimention2", "Hierarchy1", "Hierarchy2", "Hierarchy3"]
)

enter image description here

我想对其进行转换,使其变成这样的东西:

new_df = spark.createDataFrame(
    [
        ("D1", "D2", "H1"),
        ("D1", "D2", "H2"),
        ("D1", "D2", "H3")
    ],
    ["Dimension1", "Dimention2", "Hierarchy"]
)

enter image description here

逻辑是:

whencondition = when((col("Hierarchy1").isNotNull()) & (col("Hierarchy2").isNull()) & (col("Hierarchy3").isNull()), lit("H1")).when((col("Hierarchy1").isNotNull()) & (col("Hierarchy2").isNotNull()) & (col("Hierarchy3").isNull()), lit("H2")).when((col("Hierarchy1").isNotNull()) & (col("Hierarchy2").isNotNull()) & (col("Hierarchy3").isNotNull()), lit("H3")).alias("Hierarchy")

display(df.select("Dimension1", "Dimention2", whencondition))

当然可以有任意数量的层次结构列,但最终输出我只希望有一列来显示该记录所处的层次结构级别。 我首先创建了一个列表

hierarchies = ["Hierarchy1", "Hierarchy2", "Hierarchy3"]

并得到了这样的结果:

when(reduce(lambda x, y: x & y, [(col( "`" + x + "`").isNotNull()) if x in hierarchies[:i+1] else (col( "`" + x + "`").isNull()) for x in hierarchies]), lit(hierarchies[i]))

适用于 i < len(hierarchies) ,但不幸的是没有进一步的


from pyspark.sql import SparkSession
from pyspark.sql.functions import col, lit, when

# Initialize SparkSession
spark = SparkSession.builder.appName("PivotDataFrame").getOrCreate()

# Sample DataFrame
df = spark.createDataFrame(
    [
        ("D1", "D2", "H1", None, None),
        ("D1", "D2", "H1", "H2", None),
        ("D1", "D2", "H1", "H2", "H3")
    ],
    ["Dimension1", "Dimention2", "Hierarchy1", "Hierarchy2", "Hierarchy3"]
)

# List of Hierarchy columns
hierarchies = ["Hierarchy1", "Hierarchy2", "Hierarchy3"]

# Construct the when condition dynamically
when_condition = reduce(
    lambda x, y: x.when(
        reduce(
            lambda a, b: a & b,
            [col(f"`{h}`").isNotNull() if i <= idx else col(f"`{h}`").isNull() for idx, h in enumerate(hierarchies)]
        ),
        lit(y)
    ),
    hierarchies,
    lit(None)  # Base case for when().otherwise()
).alias("Hierarchy")

# Select desired columns with the dynamic when condition
new_df = df.select("Dimension1", "Dimention2", when_condition)

# Display the result
new_df.show()

Explanation:

  1. Dynamic When Condition:
  2. We use reduce to iterate through the hierarchies list and dynamically build the when condition.
  3. For each hierarchy level i , we check if all previous hierarchy columns are not null and all subsequent columns are null.
  4. If the condition is met, we assign the current hierarchy level ( hierarchies[i] ) to the "Hierarchy" column using lit(hierarchies[i]) .

  5. Base Case:

  6. We start the reduce function with lit(None) to handle cases where none of the hierarchy conditions are met. This ensures that the "Hierarchy" column will be null if all hierarchy values are null.

  7. Select and Display:

  8. Finally, we select the desired columns ("Dimension1", "Dimention2", and the dynamically generated "Hierarchy" column) and display the resulting DataFrame.

This code will work for any number of hierarchy columns, as long as they are listed in the hierarchies list.

标签:python,pyspark
From: 78780948

相关文章

  • Docker:无法在 docker 映像中使用 pythonnet 和 |无法创建默认的 .NET 运行时,该运行时
    我正在尝试使用clrfromPythonnet使用.DLL引用将一种文件类型转换为另一种文件类型。这就是我的代码的样子-importclrclr.AddReference(dll_path)importRxLibrary#ConverttoASCFormat-----------input_file=f"./{filename}.rxd"......
  • 在 Python 中以非常高的质量保存图像
    如何以非常高的质量保存Python绘图?也就是说,当我不断放大PDF文件中保存的对象时,为什么没有任何模糊?另外,什么是最好的模式将其保存在?png,eps?或者其他的?我不能pdf,因为有一个隐藏的数字会扰乱Latexmk编译。要以非常高的质量保存Py......
  • Python字符串:提取重复和随机合并的子字符串
    重复和合并字符串的示例:16.01068.0%08p%.a.p.a.要提取的所需子字符串:16.008%p.a.完整示例:CCoonnttiinnggeennttCCoouuppoonn16.01068.0%08p%.a.p(.Ma.o(nMtholyn)thly)所需子字符串:ContingentCoupon16.008%p.a.(Monthly)我的问题是当原始......
  • Python Pandas 从使用第 3 部分 API 自动生成的 Excel 文件中读取不一致的日期格式
    我正在使用PDF4meAPI将PDF发票转换为Excel文件。API可以正确读取日期。但是,当我打开Excel文件时,日期显示不一致:某些日期以正确的格式(dd/mm/yyyy)显示,而其他日期以错误的mm/dd/yyyy格式显示。当该月的某天小于或等于12时,似乎会出现这种不一致。......
  • python-input键盘输入
     str=input("请输入:")#用户键盘输入#str表示一个字符串类型的变量,input会将读取到的字符串放入str中print(str) aa='请输入:'str=input(aa)#用户键盘输入#str表示一个字符串类型的变量,input会将读取到的字符串放入str中print(str)      ......
  • Python从0到100(四十五):从字符串到前后端分离
    前言:零基础学Python:Python从0到100最新最全教程。想做这件事情很久了,这次我更新了自己所写过的所有博客,汇集成了Python从0到100,共一百节课,帮助大家一个月时间里从零基础到学习Python基础语法、Python爬虫、Web开发、计算机视觉、机器学习、神经网络以及人工智能相关知......
  • Python的运算符与条件表达式
    一、运算符Python数据是通过使用运算符来进行操作的,与数学运算符类似,主要运用于数字计算,比较大小和逻辑运算。Python中的运算符主要包括算术运算符、赋值运算符、比较运算符、逻辑运算符和位运算符。1.算术运算符算术运算符用在数字表达式中,作用和在数学中是一样的。Python......
  • 在尝试使用 docker 运行基于 pythonnet 的项目时,找不到 C# 运行时
    屏幕截图我不断收到此错误:RuntimeError:Failedtocreateadefault.NETruntime,whichwouldhavebeen"mono"onthissystem.Eitherinstallacompatibleruntimeorconfigureitexplicitlyvia......
  • Python 在模块中使用变量
    如何将一个文件中声明的变量调用到另一个文件中?大家好我已经在file1中声明了我的变量。我的函数位于file2中,它使用该变量。如何调用主文件中声明的变量。提前致谢当然可以!以下是如何在Python中跨文件使用变量:file1.py(包含变量的文件)#在file1.p......
  • Python 类型提示和 linter
    我一直在向我们的python项目添加静态类型检查,例如像这样:fromtypingimportListfromsomethingimportMyOtherClassclassMyClass:def__init__(self)->None:self.some_var=None#type:List[MyOtherClass]但是,现在我们使用的linter(flake8和......