I'm using python 3.7 and pandas 1.0.1
I'm trying to fill a column in my dataframe following the results of two previous columns.
I have a date column, an In column (which registers when an activity is starting) and an Out column (which registers when an activity is finished).
I need a Res column, which will register the overall duration of the activity.
First I have this simple dataframe:
data = {'date':['2020-01-01','2020-01-02','2020-01-03','2020-01-04','2020-01-05','2020-01-06','2020-01-07','2020-08-01','2020-01-09','2020-01-10'],
'in':[0,0,1,0,0,0,0,1,0,0],
'out':[0,0,0,0,0,1,0,0,1,0]}
df = pd.DataFrame(data, columns=['date','in','out'])
print(df)
The resulting dataframe is as follows:
date in out
0 2020-01-01 0 0
1 2020-01-02 0 0
2 2020-01-03 1 0
3 2020-01-04 0 0
4 2020-01-05 0 0
5 2020-01-06 0 1
6 2020-01-07 0 0
7 2020-08-01 1 0
8 2020-01-09 0 1
9 2020-01-10 0 0
The result I'm trying to achieve is this:
date in out res
0 2020-01-01 0 0 0
1 2020-01-02 0 0 0
2 2020-01-03 1 0 1
3 2020-01-04 0 0 1
4 2020-01-05 0 0 1
5 2020-01-06 0 1 1
6 2020-01-07 0 0 0
7 2020-08-01 1 0 1
8 2020-01-09 0 1 1
9 2020-01-10 0 0 0
I was able to do it using iterrows:
result = 0
for index, row in df.iterrows():
if (row['in']==1):
result = 1
elif (df['out'].shift(1)[index]==1):
result = 0
df.at[index,'res'] = result
But iterrows are not very time efficient when dealing with a very big dataframe.
How can I approach this problem in a better way?
df['res'] = np.where(df['in'].eq(1), 1, np.where(df['out'].shift(1).eq(1), 1, 0), 0
?