Reputation: 503
Say I have a following DataFrame:
dfff = pd.DataFrame({"name":[["a","b","c","d"]], "value":[[["a","aa"],["b","bb"],["c","cc"],["d","dd"]]]})
name value
[a, b, c, d] [[a, aa], [b, bb], [c, cc], [d, dd]]
From this I want something like:
a b c d
[a, aa] [b, bb] [c, cc] [d, dd]
For a single row, this piece of code would work, but it does not if it has multiple rows:
for i in range(len(dfff)):
for num, val in enumerate(dfff.name[i]):
dfff[val] = [dfff.value[i][num]]
dfff.drop(["name","value"], axis = 1, inplace = True)
How do I achieve this is pandas? Thanks a lot
Edit: Example for multiple rows table:
name value
0 [a, b, c, d] [[a, aa], [b, bb], [c, cc], [d, dd]]
1 [c, d, e] [[c, cc], [d, dd], [e, ee]]
It should become:
a b c d e
[a, aa] [b, bb] [c, cc] [d, dd] None
None None [c, cc] [d, dd] [e, ee]
Upvotes: 2
Views: 55
Reputation: 71689
We can zip
the columns name
and value
inside a list comprehension then iterate over the zipped values and for each name-value pair
create the corresponding record/dict
pd.DataFrame([dict(zip(*pair)) for pair in zip(df['name'], df['value'])])
a b c d e
0 [a, aa] [b, bb] [c, cc] [d, dd] NaN
1 NaN NaN [c, cc] [d, dd] [e, ee]
Upvotes: 3
Reputation: 37
I think your easiest solution is to just transpose the table.
dfff_transposed = dfff.T # or dfff.transpose()
print(dfff_transposed)
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transpose.html
Upvotes: 0