1

I have a pd.Series that contains str representations of sets. I want to use iterable unpacking to empty all of these lists into a single container (intuitively, the syntax makes perfect sense). I'm running 3.5.2 right now.

import pandas as pd
from ast import literal_eval # builtin module
Se = pd.Series(["{'a','b','c'}", "{'d','e','f'}","{'g'}"])
[literal_eval(x) for x in Se]
# [{'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g'}]
[*literal_eval(x) for x in Se]
#   File "<ipython-input-27-692f886a59ef>", line 4
#     [*literal_eval(x) for x in Se]
#     ^
# SyntaxError: iterable unpacking cannot be used in comprehension

I want to end up w/ a set that is: {'a','b','c','d','e','f','g'} (obviously this isn't my real data but it's analogous). None of the sets are nested or anything.

Is there a way that is less verbose than (below) that uses the * unpacking operator?

set_concat = set()
for x in Se:
    for y in literal_eval(x):
        set_concat.update(y)
set_concat
{'a', 'b', 'c', 'd', 'e', 'f', 'g'}
O.rka
  • 29,847
  • 68
  • 194
  • 309

0 Answers0