代码之家  ›  专栏  ›  技术社区  ›  codebot

将df从pandas转换为PySpark时会删除列名

  •  0
  • codebot  · 技术社区  · 2 年前

    我有一个json文件,格式如下。

    {
      "fd": "Bank Account",
      "appVar": [],
      "varMode": "AABH",
      "occurred": [
        {
          "occurredTimes": 3,
          "sys": [
            {
              "varTyp": "Conf Param",
              "varCode": "P33"
            }
          ],
          "userAssignments": []
        }
      ]
    }
    

    我现有的代码是在panda中开发的,但我需要转换相同的代码才能在PySpark上运行。为此,我使用 Pandas API on Spark API 根据API,我尝试从文件中读取JSON,并将Pandas-df转换为PySpark-df,如下所示。

    import pyspark.pandas as ps
    import pandas as pd
    
    df_pandas = pd.read_json('./demoFile/in/all.json', orient='values')
    df_pyspark = ps.DataFrame(df_pandas) # ps.DataFrame([df_pandas])
    

    我需要得到 occurred 数组在转换后也是如此。但它回来了,

    预期输出:转换前

    [{'occurredTimes': 3, 'sys': [{'varTyp': 'Conf Param', 'varCode': 'P33'}], "userAssignments": []]
    

    输出:转换后

    [(3, [Row(varTyp=,'Conf Param', varCode=,'P33',)], [])]
    

    如何在使用上述API将pandas-df转换为PySpark-df的同时保留列名?

    0 回复  |  直到 2 年前
        1
  •  0
  •   Memristor    1 年前

    您可以使用更改此列 to_json ,例如。

    from pyspark.sql.functions import to_json
    
    df_pyspark = df_pyspark.withColumn("occurred", to_json("occurred"))
    

    给予 ocurred 列:

    [{"occurredTimes":3,"sys":[{"varTyp":"Conf Param","varCode":"P33"}],"userAssignments":[]}]
    

    如果您的代码失败,请尝试在以下步骤之前创建带有模式的PySpark数据帧:

    json_schema = StructType(
        [
            StructField("fd", StringType(), True),
            StructField("appVar", ArrayType(StringType()), True),
            StructField("varMode", StringType(), True),
            StructField(
                "occurred",
                ArrayType(
                    StructType(
                        [
                            StructField("occurredTimes", IntegerType(), True),
                            StructField(
                                "sys",
                                ArrayType(
                                    StructType(
                                        [
                                            StructField("varTyp", StringType(), True),
                                            StructField("varCode", StringType(), True),
                                        ]
                                    )
                                ),
                                True,
                            ),
                            StructField("userAssignments", ArrayType(StringType()), True),
                        ]
                    )
                ),
                True,
            ),
        ]
    )