I am new to Python.
Suppose I have DataFrame, and want to switch selected data of all rows with similar id.
For example:
| id | Gender | Name | Hobby | Food |
+------+--------+---------+------------+-----------+
| 1111 | Male | Robert | Swim | Ice-cream |
| 1112 | Female | Natasha | Football | Pizza |
| 1111 | Female | Misa | Volleyball | Pasta |
| 1112 | Male | Rick | Sleep | Hamburger |
| 1113 | Male | Rondo | Read | Rice |
+------+--------+---------+------------+-----------+
Expected output:
+------+--------+---------+------------+-----------+
| id | Gender | Name | Hobby | Food |
+------+--------+---------+------------+-----------+
| 1111 | Male | Robert | Volleyball | Pasta |
| 1112 | Female | Natasha | Sleep | Hamburger |
| 1111 | Female | Misa | Swim | Ice-cream |
| 1112 | Male | Rick | Football | Pizza |
| 1113 | Male | Rondo | Read | Rice |
+------+--------+---------+------------+-----------+
So what I want to do is to switch data (In this example only Hobby and Food) between people with same id, but name and gender remain the same.
So basicly, on first row, id 1111, Gender is Male, Name is Robert - Hobby will be Volleyball and Food will be Pasta. On second row, id 1111, Gender is female name is Misa - hobby will be swim and food will be ice-cream. And do the same for the id 1112 as well. I do not have any idea at the moment, except for writing some loop and then use empty DataFramme to append and switch. Thank you all!!
Instead of swapping other columns, I choose to swap Name
and Gender
:
def swap(x):
x[['Gender','Name']] = x[['Gender','Name']].values[::-1]
return x
df.groupby('id').apply(swap)
Output:
id Gender Name Hobby Food
0 1111 Female Misa Swim Icecream
1 1112 Male Rick Football Pizza
2 1111 Male Robert Volleyball Pasta
3 1112 Female Natasha Sleep Hamburger
4 1113 Male Rondo Read Rice
Or if you insist on the correct order, then swap the other columns:
def swap2(x):
x[['Hobby','Food']] = x[['Hobby','Food']].values[::-1]
return x
print(df.groupby('id').apply(swap2))
Output:
id Gender Name Hobby Food
0 1111 Male Robert Volleyball Pasta
1 1112 Female Natasha Sleep Hamburger
2 1111 Female Misa Swim Icecream
3 1112 Male Rick Football Pizza
4 1113 Male Rondo Read Rice
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments