Raam
0
Q:

pandas - unlist values and put in a row

# 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)}
    ).assign(**{lst_col:np.concatenate(df[lst_col].values)})[df.columns]



# 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
                lst_col_1:np.concatenate(df1[lst_col_1].values),
                lst_col_2:np.concatenate(df1[lst_col_2].values) 
                })
0

New to Communities?

Join the community