Reputation: 57
Hi all I have been trying to convert this DataFrame
col_1 col_2 col_3
item1 item2 item3
$1xx $2xx $3xx
to this output:
col_1 NaN col_2 NaN col_3 NaN
item1 $1xx item2 $2xx item3 $3xx
Upvotes: 2
Views: 59
Reputation: 863301
I think you can avoid duplicated and also NaN
s columns, so here is alternative with DataFrame.unstack
, flatten MultiIndex Series
anf create one row DataFrame by Series.to_frame
with trnspose by DataFrame.T
:
s = df.unstack()
s.index = s.index.map(lambda x: f'{x[0]}_{x[1]}')
df = s.to_frame().T
print (df)
col_1_0 col_1_1 col_2_0 col_2_1 col_3_0 col_3_1
0 item1 $1xx item2 $2xx item3 $3xx
Another solution with DataFrame.melt
:
df = df.reset_index().melt('index', value_name=0)
df.index = df['variable'] + '_' + df['index'].astype(str)
df = df[[0]].T
print (df)
col_1_0 col_1_1 col_2_0 col_2_1 col_3_0 col_3_1
0 item1 $1xx item2 $2xx item3 $3xx
Upvotes: 1