I need to concat several rows (up to 10) in pandas dataframe to a single row.
For example: I have such dataframe
a b
0 1 3
1 2 4
convert to
a_0 b_0 a_1 b_1
0 1 3 2 4
Merging row by row is stupid, but I have no idea how to proceed.
Use DataFrame.stack
for MultiIndex Series
, convert to one row DataFrame and last flatten MultiIndex
:
df = df.stack().to_frame().T
df.columns = df.columns.map(lambda x: f'{x[1]}_{x[0]}')
print (df)
a_0 b_0 a_1 b_1
0 1 3 2 4
Or if all values are numeric use numpy.ravel
with itertools.product
:
from itertools import product
c = [f'{x[0]}_{x[1]}' for x in product(df.columns, df.index)]
df = pd.DataFrame([df.to_numpy().ravel()], columns=c)
print (df)
a_0 a_1 b_0 b_1
0 1 3 2 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.