0

I have columns values inside a list

df1 = pd.DataFrame(
    {
        "column0": [["xx, aa", "xx, aa"]],
        "column1": [["yy, bb","yy, aa"]],
        "column2": [["cc, xx", "cc, xx"]]})

         column0         column1               column2
0   [xx, aa, xx, aa]    [yy, bb, yy, aa]    [cc, xx, cc, xx]

I want to separate all of them into multiple columns

outcome:

   column0 column1 column2 column3 column4 column5  column6  column7 column8 column9  
0   xx    aa   xx     aa    yy    bb    yy     aa      cc       xx     cc     xx

Any ideas?

EDIT:

The suggested question is not relevant to by problem as I have multiple columns and not just one

3
  • stackoverflow.com/questions/70203071/… Commented Dec 2, 2021 at 19:18
  • Shouldn't there be 12 columns instead of 10? Commented Dec 2, 2021 at 19:27
  • It's not clear if there should be 8 or 12 columns in the final dataframe. (Each list has 2 string values, not 4.) Commented Dec 2, 2021 at 19:33

1 Answer 1

0

I think it's a better approach to clean your data prior to instantiating a pandas DataFrame.

Here's an option you can take given the data structure you posted:

import pandas as pd

init_dict = {"column0": [["xx, aa", "xx, aa"]], "column1": [["yy, bb", "yy, aa"]], "column2": [["cc, xx", "cc, xx"]]}

pd_dict = {}
col_counter = 0
for _, value in init_dict.items():
    for item in value.pop():
        for inner_item in item.split(","):
            pd_dict[f"column{col_counter}"] = [inner_item.strip()]
            col_counter += 1

pd.DataFrame(pd_dict)
>>>  column0 column1 column2 column3 column4 column5 column6 column7 column8  \
0      xx      aa      xx      aa      yy      bb      yy      aa      cc   

  column9 column10 column11  
0      xx       cc       xx  
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.