1

I am trying to identify patterns in a DF column: a streak of 4 zeros (represent rainy days) followed by 1 (dry day) in column "dry day". When this pattern is identified, 1 is to be marked in column "streaky". The result is not consistent: there are correct matches (2012-10-23) as well as false ones (2012-10-17). What goes wrong?

enter image description here

for i in range(0,2641): 
    if sum(X2.iloc[i:(i+4),4]) ==0 and X2.iloc[(i+5),4] ==1: 
        X2.iloc[(i+5),16] = 1

1 Answer 1

0

I created a test dataframe (with only the columns necessary and 16 rows) and I am getting the expected results.

I also manually created an "expected" column to compare the "actual" (streaky) column to.

I am using Python 3.8.3 64-bit and running in VSCode

import pandas as pd

data = {'Date':  ['2012-10-13', '2012-10-14', '2012-10-15', '2012-10-16', '2012-10-17', '2012-10-18','2012-10-19', '2012-10-20', '2012-10-21', '2012-10-22','2012-10-23','2012-10-24' , '2012-10-25','2012-10-26', '2012-10-27', '2012-10-28', '2012-10-29' ],
    'dry day': [0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0],
    'expected':['', '', '', '',  '', 'none', 'none', 'none', 'none', 'none', '1', 'none', 'none', 'none', 'none', 'none', 'none']
    }

X2 = pd.DataFrame (data, columns = ['Date','dry day', 'expected'])
X2["actual"] = ""

for i in range(0,12): 
    if sum(X2.iloc[i:(i+4),1]) ==0 and X2.iloc[(i+5),1] ==1: 
        print(str(X2.iloc[i+5,0]) + " : is Streaky" )
        X2.iloc[(i+5),3] = 1
    else:
        X2.iloc[(i+5),3] = 'none'

print(X2)

Results as Expected

1
  • I am getting the warning: "SettingWithCopyWarning:A value is trying to be set on a copy of a slice from a DataFrame." probably here is the answer: dataquest.io/blog/settingwithcopywarning - as I was using a subset/ copy of the original pd DF. Thanks for checking the code/ logic!
    – NoaMi
    Jul 9, 2020 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.