I am working with a piece of code, which is supposed to read the columns in each row of the data and based on the value of that cell, create a file name to pick. I was required to use the if elif else statements but the code sometimes picks the right value, sometimes not. So,
This is the data sample:
S.No File refrence Time Detection_Location
1 5008_P1_272 2019-04-24 16:15:53 CV22
2 5007_P2_467 2019-04-25 19:00:22 CV23
The code I am using for this operation is:
# Converting columns to datetime format
df['Time'] = pd.to_datetime(df['Time'], errors = 'coerce').dt.date
#Stripping the datetime
df['Time'] = pd.to_datetime(df['Time'])
df['Time'] = df['Time'].dt.strftime('%Y-%m-%d')
df[['Stripped Year', 'Stripped Month','Strip date']] = df['Time'].str.split(pat = "-", n=2, expand = True)
# Creating the file name string
for i in df.index:
First = 'PHD'
#for s in df['Stripped Year']:
s = df.iloc[i]['Stripped Year']
second1 = s[2:]
print(second1)
s1 = df.iloc[i]['Stripped Month']
second2 = s1
print(second2)
if second2 == '02':
second3 = '28'
if second2 == '01' or '03' or '05' or '07' or '08' or '10' or '12':
second3 = '31'
if second2 == '04' or '06' or '09' or '11':
second3 = '30'
print(second3)
s2 = df.iloc[i]['Detection_Location']
if s2 == 'CV22':
second4 = 'L1'
elif s2 == 'CV23':
second4 = 'L2'
elif s2 == 'CV3':
second4 = 'LC'
print(second4)
PHD_File_Name = First + ' ' +second1+second2+'01' + ' ' +second1+second2+second3 + ' ' + second4 + '_transformed' + '.xlsx'
print(PHD_File_Name)
My code seems to work well in picking the month value( second3 value from second2 value) sometimes and sometimes it does not pick the right month. I used if elif else and if else else statement but the performance of the code is not consistent. Please help what am I doing wrong.
The desired output for the first row of the data should be:
second1 = 2019
second2 = 04
second3 = 30
Thanks