【问题标题】:Pyspark: convert rdd with different keys to spark dataframePyspark:将具有不同键的rdd转换为火花数据帧
【发布时间】:2017-11-28 20:46:28
【问题描述】:

我有一种情况,我的 rdd 键在每个字典中都不同,有些具有比其他更多和不同的键。

因此,我无法使用toDF() 直接隐藏它们。有人有更好的主意吗?

list1 = [{'this':'bah', 'is': 'bah'}, 
         {'this': 'true', 'is': 'false'}, 
         {'this': 'true', 'is': 'false', 'testing':'bah'}]

rdd = sc.parallelize(list1)
rdd.map(lambda x: Row(**x)).toDF().show()

【问题讨论】:

    标签: python apache-spark pyspark spark-dataframe


    【解决方案1】:

    我想没有现成的解决方案。

    乍一看,我要做的是创建一个包含我集合中所有列的set() 列表,然后遍历每一行以创建所有不存在的列并将它们初始化为None

    list1 = [{'this':'bah', 'is': 'bah'}, 
             {'this': 'true', 'is': 'false'}, 
             {'this': 'true', 'is': 'false', 'testing':'bah'}]
    
    # create a list of unique available keys   
    keys = set().union(*(item.keys() for item in list1))
    
    for key,item in enumerate(list1):
        # find which ones are not in the current row
        difference = [i for i in keys if i not in item]
        if len(difference) > 0:
            # create them
            for i in range(0,len(difference)):
                item[difference[i]] = None
    

    然后您的集合具有相同数量的列:

    [{'this': 'bah', 'is': 'bah', 'testing': 无}, {'this': 'true', 'is': 'false', 'testing': 无}, {'this': 'true', 'is': 'false', 'testing': 'bah'}]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-25
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      相关资源
      最近更新 更多