Explode column of list to multiple rows
Pandas >= 0.25
Pandas can do this in a single function call via df.explode
.
df.explode('column_x')
column_a column_b column_x
0 a_1 b_1 c_1
0 a_1 b_1 c_2
1 a_2 b_2 d_1
1 a_2 b_2 d_2
Note that you can only explode a Series/DataFrame on one column.
Pandas < 0.25
Call np.repeat
along the 0th axis for every column besides column_x
.
df1 = pd.DataFrame(
df.drop('column_x', 1).values.repeat(df['column_x'].str.len(), axis=0),
columns=df.columns.difference(['column_x'])
)
df1['column_x'] = np.concatenate(df['column_x'].values)
df1
column_a column_b column_x
0 a_1 b_1 c_1
1 a_1 b_1 c_2
2 a_2 b_2 d_1
3 a_2 b_2 d_2
You can repeat index values:
lens = df['column_x'].str.len()
a = np.repeat(df.index.values, lens)
print (a)
[0 0 1 1]
df = df.loc[a].assign(column_x=np.concatenate(df['column_x'].values)).reset_index(drop=True)
print (df)
column_a column_b column_x
0 a_1 b_1 c_1
1 a_1 b_1 c_2
2 a_2 b_2 d_1
3 a_2 b_2 d_2