I have a pandas data frame like this:
df = pandas.DataFrame({
'Grouping': ["A", "B", "C"],
'Elements': ['[\"A1\"]', '[\"B1\", \"B2\", \"B3\"]', '[\"C1\", \"C2\"]']
}).set_index('Grouping')
so
Elements
Grouping
===============================
A ["A1"]
B ["B1", "B2", "B3"]
C ["C1", "C2"]
i.e. some lists are encoded as strings-as-lists. What is a clean way to reshape this into a tidy data set like this:
Elements
Grouping
====================
A A1
B B1
B B2
B B3
C C1
C C2
without resorting to a for-loop? The best I can come up with is:
df1 = pandas.DataFrame()
for index, row in df.iterrows():
df_temp = pandas.DataFrame({'Elements': row['Elements'].replace("[\"", "").replace("\"]", "").split('\", \"')})
df_temp['Grouping'] = index
df1 = pandas.concat([df1, df_temp])
df1.set_index('Grouping', inplace=True)
but that's pretty ugly.