Using pandas data frame in python:
I am trying to get the following data from a data frame and cant fix my loop to get the proper result.
A small sample of the data set:
BERTH FROM_BERTH BI
29 H2 0
29 09 0
29 J5 0
C5 NaN 1
J4 NaN 1
J2 NaN 1
Here is part of the dataset ( the relevant columns i need to use) and here is what i want the output to look like :
29, H2, 09, J5, C5, J4, J2
that is: if BI is 0 i want the value from BERTH and then the values of FROM_BERTH till BI becomes 1, and then goes back to giving me the BERTH ( untill BI becomes 1 again, so on ans so forth ).
Here are the following codes i have tried and their results :
test_berth2 = []
for i in range(0,6):
if df3_test.loc[i,'BI'] == 0 & df3_test.iloc[i,21] != df3.iloc[i-1,21]:
test_berth2.append(df3_test.loc[i,'BERTH'])
test_berth2.append(df3_test.loc[i,'FROM_BERTH'])
elif df3_test.loc[i,'BI'] == 0 & df3_test.iloc[i,21] == df3.iloc[i+1,21]:
test_berth2.append(df3_test.loc[i,'FROM_BERTH'])
else :
test_berth2.append(df3_test.loc[i,'BERTH'])
test_berth2
result :
['29', 'H2', '29', '09', '29', 'J5', 'C5', 'J4', 'J2']
Loop 2 :
for i in range(0,6):
if df3_test.iloc[i,21] == 0:
print (df3_test.loc[i,'BERTH'])
while df3_test.iloc[i,21] == 0:
print (df3_test.loc[i,'FROM_BERTH'])
i = i+1
else:
print (df3_test.loc[i,'BERTH'],'1')
result :
29, H2, 09, J5, 29, 09, J5, 29, J5, C5 1, J4 1, J2 1
PS :the iloc to column 21 is 'BI' btw