pythonarraysempty-list

how to return None for empty array in python?


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)]

Solution

  • 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])]