0

I have a pandas dataframe in which multiple(3) column contains values corresponding to the next column. I want to split each row into multiple rows accordingly and create a new row per entry. For example, 'source' should become

*source

Time (magazine)

WarnerMedia

WarnerMedia

WarnerMedia

U.S. Securities and Exchange Commission

WarnerMedia

AOL *

The dataframe is of the format

ID source target type
0 ["': 'Time (magazine)", "': 'WarnerMedia", "': 'WarnerMedia", "': 'WarnerMedia", "': 'U.S. Securities and Exchange Commission", "': 'WarnerMedia", "': 'AOL"] ["': 'WarnerMedia", "': 'Time (magazine)", "': 'Time (magazine)", "': 'U.S. Securities and Exchange Commission", "': 'WarnerMedia", "': 'AOL", "': 'WarnerMedia"] ["': 'owned by", "': 'subsidiary", "': 'owned by", "': 'subsidiary", "': 'subsidiary", "': 'subsidiary", "': 'subsidiary"]
1 ["': 'Federal Reserve", "': 'Bank of America", "': 'London", "': 'New York (state)"] ["': 'London", "': 'New York (state)", "': 'Federal Reserve", "': 'Bank of America"] ["': 'headquarters location", "': 'headquarters location", "': 'headquarters location", "': 'headquarters location"]

I would require the data to be formatted in the following way :

ID source target type
0 Time (magazine) WarnerMedia owned by
0 WarnerMedia Time (magazine) subsidiary
0 WarnerMedia Time (magazine) owned by
0 WarnerMedia U.S. Securities and Exchange Commission subsidiary
0 U.S. Securities and Exchange Commission WarnerMedia subsidiary
0 WarnerMedia AOL subsidiary
0 AOL WarnerMedia subsidiary

and so on..

I was using pandas explode function, but I could make it work for only one column, I would like to make it work for multiple columns at the same.

Thanks in Advance

1
  • ignore my previous comment. you can do this, and pandas does enforce that each list be the same length. Commented Nov 9, 2022 at 19:59

1 Answer 1

2

You can pass a list to pandas.DataFrame.explode:

exploded = df.explode(["source", "target", "type"])

To explode multiple columns, each list within each cell must have an identical length to the lists in the other cells in the row.

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.