pandas unlist values and put in a row

Solutions on MaxInterview for pandas unlist values and put in a row by the best coders in the world

showing results for - "pandas unlist values and put in a row"
Kris
03 Sep 2018
1# Version for one list column to put in signle row
2lst_col = 'my_list_var'
3
4r = pd.DataFrame({
5      col:np.repeat(df[col].values, df[lst_col].str.len())
6      for col in df.columns.drop(lst_col)}
7    ).assign(**{lst_col:np.concatenate(df[lst_col].values)})[df.columns]
8
9
10
11# Version for multiple list column and put them in signle row --> long format
12lst_col = 'my_list_var'
13lst_col_1 = 'my_list_var_1'
14lst_col_2 = 'my_list_var_2'
15
16
17r = pd.DataFrame({
18      col:np.repeat(df1[col].values, df1[lst_col].str.len())          # Repeat column values N times where N is the lenght of list                         
19      for col in df1.columns}                                         # np.concatenate() --> flatten all values in the list column and get a 1D vector
20    ).assign(**{lst_col:np.concatenate(df1[lst_col].values),          # ** --> out data into a dictionary
21                lst_col_1:np.concatenate(df1[lst_col_1].values),
22                lst_col_2:np.concatenate(df1[lst_col_2].values) 
23                })