2

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]
2
  • 1
    could you give an example of desired multiple rows processing? Commented May 19, 2021 at 19:24
  • @Stepan I just added an example. Commented May 19, 2021 at 19:37

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

But it does not give what I want ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.