I wish to flatten(I am not sure whether is the correct thing to call it flatten) the columns with rows. multiple rows into single row with column change to column_rows I have a dataframe as below:
JavaScript
x
6
1
data = {"a":[3,4,5,6],
2
"b":[88,77,66,55],
3
"c":["ts", "new", "thing", "here"],
4
"d":[9.1,9.2,9.0,8.4]}
5
df = pd.DataFrame(data)
6
my current output is:
JavaScript
1
6
1
a b c d
2
0 3 88 ts 9.1
3
1 4 77 new 9.2
4
2 5 66 thing 9.0
5
3 6 55 here 8.4
6
my expected otput:
JavaScript
1
3
1
a_0 a_1 a_2 a_3 b_0 b_1 b_2 b_3 c_0 c_1 c_2 c_3 d_0 d_1 d_2 d_3
2
0 3 4 5 6 88 77 66 55 ts new thing here 9.1 9.2 9.0 8.4
3
from shape (4,4) to (1, 16)
Advertisement
Answer
Update let’s use the walrus operator
new in Python 3.8 to create a one-liner:
JavaScript
1
4
1
(df_new := df.unstack().to_frame().T).set_axis(
2
[f"{i}_{j}" for i, j in df_new.columns], axis=1
3
)
4
Output:
JavaScript
1
3
1
a_0 a_1 a_2 a_3 b_0 b_1 b_2 b_3 c_0 c_1 c_2 c_3 d_0 d_1 d_2 d_3
2
0 3 4 5 6 88 77 66 55 ts new thing here 9.1 9.2 9.0 8.4
3
Try this, using unstack
, to_frame
and transpose. Next, flatten the column headers using list comprehension:
JavaScript
1
4
1
df_new = df.unstack().to_frame().T
2
df_new.columns = [f'{i}_{j}' for i, j in df_new.columns]
3
df_new
4
Output:
JavaScript
1
3
1
a_0 a_1 a_2 a_3 b_0 b_1 b_2 b_3 c_0 c_1 c_2 c_3 d_0 d_1 d_2 d_3
2
0 3 4 5 6 88 77 66 55 ts new thing here 9.1 9.2 9.0 8.4
3