I have dataframe like below:
import pandas as pd
JavaScript
x
10
10
1
df = pd.DataFrame.from_dict(
2
{
3
'Name': ['Jenny', 'Matt', 'Jenny', 'Matt', 'Jenny', 'Matt', 'Jenny', 'Matt'],
4
'Year': [2020, 2021, 2022, 2020, 2021, 2022, 2020, 2021],
5
'Income': [10000, 11000, 9000, 12000, 13000, 11000, 14000, 15000],
6
'Gender': ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M']
7
}
8
)
9
print(df)
10
Output:
JavaScript
1
10
10
1
Name Year Income Gender
2
0 Jenny 2020 10000 F
3
1 Matt 2021 11000 M
4
2 Jenny 2022 9000 F
5
3 Matt 2020 12000 M
6
4 Jenny 2021 13000 F
7
5 Matt 2022 11000 M
8
6 Jenny 2020 14000 F
9
7 Matt 2021 15000 M
10
i want to append two rows into single row by using Gender (both F and M should be in one row). i dont bother on increasing the columns
My expected output should be:
JavaScript
1
6
1
Name Year Income Gender Name1 Year1 Income1 Gender1
2
Jenny 2020 10000 F Matt 2021 11000 M
3
Jenny 2022 9000 F Matt 2020 12000 M
4
Jenny 2021 13000 F Matt 2022 11000 M
5
Jenny 2020 14000 F Matt 2021 15000 M
6
Any suggestions how to do this would be helpful.
Advertisement
Answer
Split the dataframe into two dataframes (one for Gender = 'F'
and one for Gender = 'M'
) and concatenate them:
JavaScript
1
8
1
df1 = df[df.Gender == 'F'].reset_index(drop=True)
2
df2 = df[df.Gender == 'M'].reset_index(drop=True)
3
df2.columns = [i + '1' for i in df.columns]
4
5
result = pd.concat([df1, df2], axis=1)
6
7
print(result)
8
Output:
JavaScript
1
6
1
Name Year Income Gender Name1 Year1 Income1 Gender1
2
0 Jenny 2020 10000 F Matt 2021 11000 M
3
1 Jenny 2022 9000 F Matt 2020 12000 M
4
2 Jenny 2021 13000 F Matt 2022 11000 M
5
3 Jenny 2020 14000 F Matt 2021 15000 M
6