I have two pandas columns that are supposed to represent the interactions of 2 types of chemicals. I want the ‘user’ type of ID to be in one column and the id2 column to only have the ‘id/’ ID types. This basically means just switch the first two columns for any rows that are not in this order. But the thing is, for each row where I switch the order, I also need to flip the True/False value for the third column and I have about 7 other columns that I want to stay the same. I have a small example below.
JavaScript
x
10
10
1
id1 id2 a_acting othercol1 othercol2
2
user/123 id/308 True
3
4
id/328 user/219 True
5
6
user/321 id/328 False
7
8
user/328 id/321 False
9
10
desired
JavaScript
1
10
10
1
id1 id2 a_acting othercol1 othercol2
2
user/123 id/308 True
3
4
user/219 id/328 False
5
6
user/321 id/328 False
7
8
user/328 id/321 False
9
10
Advertisement
Answer
Use boolean indexing:
JavaScript
1
9
1
# identify incorrect rows
2
m = df['id1'].str.startswith('id')
3
4
# swap
5
df.loc[m, 'id1'], df.loc[m, 'id2'] = df.loc[m, 'id2'], df.loc[m, 'id1']
6
7
# flip boolean
8
df.loc[m, 'a_acting'] = ~df.loc[m, 'a_acting']
9