I have two dataframes. The FIRST one, shown below, has three columns.
Col_1 Col_2 Col_3
aaa dfd ccc
sdf jjj sge
rty fgh rtg
hji dfg hyt
lkj bgh dcf
In each row, there is one element that is the same as one of the elements in the SECOND dataframe shown below (the elements in the second dataframe do not have to have any a specific order, of course).
list
ccc
sge
fgh
dfg
dcf
My goal is to iterate through each row in the FIRST dataframe and find that common element with the SECOND dataframe. This is followed by bringing that element ahead to the beginning of the row. The expected result is as follows:
Expected result
Col_1 Col_2 Col_3
ccc aaa dfd
sge sdf jjj
fgh rty rtg
dfg hji hyt
dcf lkj bgh
Any help will be appreciated !!
Using the .apply method of the pandas DataFrame you can do it in one line. This will be faster than manually iterating over the rows.
It only uses pandas and works at a row level by first checking if any of the rows elements are in ls, sorts the returned binary indicator (True to front of row) and then re-indexes the row to be sorted in this order. It then broadcasts the results back onto the original row.
import pandas as pd
df = pd.DataFrame({'col1':['aaa','sdf','rty','hji','lkj'],
'col2':['dfd','jjj','fgh','dfg','bgh'],
'col3':['ccc','sge','rtg','hyt','dcf']})
ls = pd.Series(['ccc','sge','fgh','dfg','dcf'])
df = df.apply(lambda x: x[(~x.isin(ls)).argsort()],
axis=1,
result_type='broadcast')
Returns:
col1 col2 col3
0 ccc aaa dfd
1 sge sdf jjj
2 fgh rty rtg
3 dfg hji hyt
4 dcf lkj bgh
Why not try using apply, isin and tolist:
print(df.apply(lambda x: x[x.isin(ls)].tolist() + x[~x.isin(ls)].tolist(), axis=1))
Output:
col1 col2 col3
0 ccc aaa dfd
1 sge sdf jjj
2 fgh rty rtg
3 dfg hji hyt
4 dcf lkj bgh
I simple load each row and get the one that is in ls and make it the first value, by adding the rest to the end with itself being the first, using isin and tolist and +.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With