0

I have a dataframe with two columns. Column one contains an integer, the second column a list with multiple items, which also can be empty. I want to return a list with tuples, in which the first part of the tuple is the integer from col1, and the second part of the tuple is the integer from col2, listing in total all possible outcomes. Input:

    col1    col2
0   909101  [1396920, 3094857]
1   21095887    [8383568]
2   8383568 [21095887]
3   2408689 []

desired output:

[(909101, 1396920),
(909101, 3094857),
 (21095887, 8383568),
 (8383568, 21095887),
 (2408689, None)]

So far, I have these, but it only outputs tuples for non empty inputs.

[(df[col1][i],df[col2][i][j]) 
            for i in range(len(df))
            for j in range(len(df[col2][i]))]
[(909101, 1396920),
(909101, 3094857),
 (21095887, 8383568),
 (8383568, 21095887)]
1
  • Have you tried doing this with normal for loops? This will make it easier for you to add a simple if statement to handle the special case. Commented Nov 17, 2021 at 12:49

1 Answer 1

1

One quick and dirty fix, turning the second loop into a normal for-each loop:

[(df[col1][i], x) 
            for i in range(len(df))
            for x in (df[col2][i] or [None])]
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.