【问题标题】:How to convert combined data set to dataframe in Python如何在 Python 中将组合数据集转换为数据框
【发布时间】:2021-04-28 02:12:03
【问题描述】:

这是我的输入列表:

input_data = ['ned','etainclub','codingart','codingman','ksc','imrahelk', 'newbijohn','coinfarmer165','ponzipanda','blockchainstudio','jisoooh0202', 'jamieinthedark','xinnong','bbooaae','onehand','osyvv','bluengel','jungjunghoon','duplicate','lucky2']

我已经定义了函数predict,在对数据调用这个函数之后,我得到了这个结果:

[{'ned': 'male'}, {'etainclub': 'male'}, {'codingart': 'male'}, {'codingman': 'male'}, {'ksc': 'male'}, {'imrahelk': 'male'}, {'newbijohn': 'male'}, {'coinfarmer165': 'male'}, {'ponzipanda': 'female'}, {'blockchainstudio': 'male'}, {'jisoooh0202': 'male'}, {'jamieinthedark': 'male'}, {'xinnong': 'male'}, {'bbooaae': 'female'}, {'onehand': 'male'}, {'osyvv': 'male'}, {'bluengel': 'male'}, {'jungjunghoon': 'male'}, {'duplicate': 'female'}, {'lucky2': 'male'}]

下面这张表是我想从上面的数据中得到的目标格式:

name gender
ned male
etainclub male
duplicate female
lucky2 male

【问题讨论】:

  • 嗨,Junoy,欢迎来到 StackOverflow!您能否使用文本编辑器中的代码格式化程序重新格式化问题中的代码?
  • @ebeb9,我更新了。还好吗?

标签: python-3.x list dataframe apache-spark-sql


【解决方案1】:

predict_output 是一个字典列表。您可以首先通过获取每个 dict 元素的项目将其转换为列表列表,然后将结果传递给spark.createDataFrame()

import itertools

data = itertools.chain(*[p.items() for p in predict_output])

df = spark.createDataFrame(data, ["name", "gender"])
df.show(5)

#+---------+------+
#|     name|gender|
#+---------+------+
#|      ned|  male|
#|etainclub|  male|
#|codingart|  male|
#|codingman|  male|
#|      ksc|  male|
#+---------+------+

【讨论】:

    【解决方案2】:

    不使用 itertools 的替代解决方案:

    df = spark.createDataFrame(
        [[k,v] for i in predict_output for k,v in i.items()],
        ['name', 'gender']
    )
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 2016-06-02
      • 1970-01-01
      • 2021-01-22
      • 2016-06-12
      • 2021-05-14
      • 2018-01-07
      • 2017-02-19
      • 2020-08-15
      相关资源
      最近更新 更多