I am working on a large pandas adatframe with about 100 million rows and 2 columns. I want to iterate over the dataframe and efficiently set a third column depending on the values of col1 and col2. This is what I am currently doing -
df[col3] = 0
for idx, row in df.iterrows():
val1 = row[col1]
val2 = row[col2]
df1 = df.loc[(df.col1 == val2) & (df.col2 == val1)]
if len(df1) > 0:
df.loc[(df.col1 == val2) & (df.col2 == val1), col3] = 1
Example:
df = pd.DataFrame({'col1':[0,1,2,3,4,11], 'col2':[10,11,12,4,3,0]})
>> df.head()
col1 col2
0 0 10
1 1 11
2 2 12
3 3 4
4 4 3
5 3 10
I want to add 'col3' such that last 2 rows of the third column are
1. Think of it as a reverse_edge column which is 1 when for each
(val1, val2) in col1, col2 there is a (val2, val1) in col1, col2
col1 col2 col3
0 0 10 0
1 1 11 0
2 2 12 0
3 3 4 1
4 4 3 1
5 11 0 0
What is the most efficient way to do this computation? It is currently taking me hours to traverse the entire dataframe.
EDIT: Think of each value in col1 and corresponding value in col2 as an edge in a graph (val1 -> val2). I want to know if a reverse edge exists or not (val2 -> val1).