How to explode a list inside a Dataframe cell into separate rows

后端 未结 11 2367
天命终不由人
天命终不由人 2020-11-22 10:20

I\'m looking to turn a pandas cell containing a list into rows for each of those values.

So, take this:

If I\'d like to unpack and stack the value

11条回答
  •  误落风尘
    2020-11-22 11:08

    Extending Oleg's .iloc answer to automatically flatten all list-columns:

    def extend_iloc(df):
        cols_to_flatten = [colname for colname in df.columns if 
        isinstance(df.iloc[0][colname], list)]
        # Row numbers to repeat 
        lens = df[cols_to_flatten[0]].apply(len)
        vals = range(df.shape[0])
        ilocations = np.repeat(vals, lens)
        # Replicate rows and add flattened column of lists
        with_idxs = [(i, c) for (i, c) in enumerate(df.columns) if c not in cols_to_flatten]
        col_idxs = list(zip(*with_idxs)[0])
        new_df = df.iloc[ilocations, col_idxs].copy()
    
        # Flatten columns of lists
        for col_target in cols_to_flatten:
            col_flat = [item for sublist in df[col_target] for item in sublist]
            new_df[col_target] = col_flat
    
        return new_df
    

    This assumes that each list-column has equal list length.

提交回复
热议问题