Pandas – Unlist Values And Put In A Row Code Example

Snippet 1

  # Version for one list column to put in signle row
lst_col = 'my_list_var'

r = pd.DataFrame({
      col:np.repeat(df[col].values, df[lst_col].str.len())
      for col in df.columns.drop(lst_col)}

# Version for multiple list column and put them in signle row --> long format
lst_col = 'my_list_var'
lst_col_1 = 'my_list_var_1'
lst_col_2 = 'my_list_var_2'

r = pd.DataFrame({
      col:np.repeat(df1[col].values, df1[lst_col].str.len())          # Repeat column values N times where N is the lenght of list                         
      for col in df1.columns}                                         # np.concatenate() --> flatten all values in the list column and get a 1D vector
    ).assign(**{lst_col:np.concatenate(df1[lst_col].values),          # ** --> out data into a dictionary

Copyright © Code Fetcher 2020



Leave a comment

Your email address will not be published. Required fields are marked *