mercredi 8 janvier 2020

Interval comparison not working with if-statement - python

I am working on a bit of code that would allow me to fill a dataframe with specific strings or values depending on the index value and stock everything in a dict. As a test, I wanted to fill a dataframe df with 'foo' if the index was less or equal to 3 or greater or equal to 7.

I thought the script I wrote bellow would work but it doesn't and I am afraid I am running out of ideas as to why.

letter_list = ['a', 'b', 'c']

mydict = dict()

for letter in letter_list:
    df = pd.DataFrame()
    df = df.reindex(range(10))

    for i in df.index.astype(float):
        if i <= 3 or i >= 7:        
            df['toto'] = 'foo'

        else:
            df['toto'] = 'booo'

    mydict[letter] = dict()
    mydict[letter]['toto']  = df.toto

The output of this gives me:

{'A1': {'toto': 0    foo
  1    foo
  2    foo
  3    foo
  4    foo
  5    foo
  6    foo
  7    foo
  8    foo
  9    foo
  Name: toto, dtype: object}}

Instead of:

{'a': {'toto': 0    foo
  1    foo
  2    foo
  3    foo
  4    booo
  5    booo
  6    booo
  7    foo
  8    foo
  9    foo
  Name: toto, dtype: object}}

I thought of replacing if i <= 3 or i >= 7: with if 3 <= i <= 7: but I still get the same result. Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire