1

How to createDataFrame from a dict? I use the following code and meet errors.

from pyspark import SparkContext, SQLContext
sc = SparkContext.getOrCreate()
spark = SQLContext(sc)

result_dict = {'a':3,'b':44}
data = list(map(list, result_dict.items()))
f_rdd = spark.createDataFrame(data, ["A", "B"]).repartition(1)

Error:

AttributeError                      Traceback (most recent call last)
<ipython-input-10-a25453caa1c3> in <module>
      5 result_dict = {'a':3,'b':44}
      6 data = list(map(list, result_dict.items()))
----> 7 f_rdd = spark.createDataFrame(data, ["A", "B"]).repartition(1)

AttributeError: 'SQLContext' object has no attribute 'createDataFrame'
4
  • I tried your piece of code as well. it works. Commented Jul 2, 2020 at 23:56
  • which spark version are you using? Commented Jul 3, 2020 at 0:07
  • @rosefun Your code works perfectly fine. I have written down examples of how to create different kinds of PySpark dataframes here in case you are interested. Commented Jul 4, 2020 at 19:48
  • Yes, the code is correct, and I have solved the problem. Commented Jul 5, 2020 at 12:54

1 Answer 1

1

You can try this way:

from pyspark.sql import SparkSession

spark = SparkSession.builder \
    .appName('so')\
    .getOrCreate()

sc = spark.sparkContext

map = {'a': 3, 'b': 44}
data = sc.parallelize([(k, v) for k, v in map.items()]).toDF(['A', 'B'])

data.show()

# +---+---+
# |  A|  B|
# +---+---+
# |  a|  3|
# |  b| 44|
# +---+---+
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.