'How to convert each row of a dataframe to new column use concat in python
If I have dataframes,
df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
"C": ["C0", "C1", "C2", "C3"],
"D": ["D0", "D1", "D2", "D3"],
},
index=[0, 1, 2, 3],)
df2 = pd.DataFrame(
{
"A": ["A4", "A5", "A6", "A7"],
"B": ["B4", "B5", "B6", "B7"],
"C": ["C4", "C5", "C6", "C7"],
"D": ["D4", "D5", "D6", "D7"],
},
index=[4,5,6,7],)
I want to use pd.concat to combine these two dataframes as
dfnew = pd.concat([df1.loc[0],
df1.loc[1],
df1.loc[2],
df1.loc[3],
df2.loc[4],
df2.loc[5],
df2.loc[6],
df2.loc[7]],
axis=0,sort=False)
dfnew = dfnew.to_frame().transpose()
dfnew is a 1row x 32 columns dataframe. But how about I have many rows in df1 and df2, or I want to combine different number of rows of df1 and df2 in a loop? What can I do for the concat .loc[] part? Or is there another way to do this?
Thank you ahead.
Solution 1:[1]
IIUC, you could stack the individual dataframes, concat and reshape:
dfnew = pd.concat([df1.stack(), df2.stack()]).droplevel(0).to_frame().T
output:
A B C D A B C D A B C D A B C D A B C D A B C D A B C D A B C D
0 A0 B0 C0 D0 A1 B1 C1 D1 A2 B2 C2 D2 A3 B3 C3 D3 A4 B4 C4 D4 A5 B5 C5 D5 A6 B6 C6 D6 A7 B7 C7 D7
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
