PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 22, 2022

[FIXED] How to set multiple conditions using an iteration for python

 November 22, 2022     iteration, multiple-conditions, pandas, pandas-loc, python     No comments   

Issue

I am looking for a gradient pattern on my dataframe as follows:

df.loc[(
        (df['A'].shift(-0).lt(1.7)) &
        (df['A'].shift(-1).lt(1.7)) &
        (df['A'].shift(-2).lt(1.7)) &
        (df['A'].shift(-3).lt(1.7)) &
        (df['A'].shift(-4).lt(1.7)) &
        (df['A'].shift(-5).lt(1.7)) &
]

The latter will return a df where 6 previous values are smaller than 1.7 for example:

the data frame will look like this (before and after):

         A
329    15.1252
330    13.1251
331     1.3125
332     1.5625
333    39.5625
346    45.6875
347    11.0000
348    11.0000
354     1.8125
355     1.8125
358     1.4375
359     1.4375
360     1.5000
361     1.5000
362     1.5000
363     1.5000
364     1.4375
365     1.4375
366     1.5000 

         A
364    1.4375
365    1.4375
366    1.5000


It works but I want to improve it. I tried many things, I think it could be something like:

parameters = [
    [0, 1.7],
    [1, 1.7],
    [2, 1.7],
    [3, 1.7],
    [4, 1.7],
    [5, 1.7],
]

conditions = ([ ' & ' .join(['(df["A"].shift(-{0}).lt({1}))'.format(x[0], x[1]) for x in parameters])])
conditions = '(' + conditions ')'
df.loc[conditions]

It seems that 'conditons' is returned as string between quotes litterally as 'conditions', so df.loc[conditions] returns a 'KeyError'

Is my first question on the website. Thanks in advance.


Solution

You can try use reduce on list

from functools import reduce

m = reduce((lambda df1, df2: df1&df2), [df['A'].shift(-s).lt(v) for s, v in parameters])
print(df.loc[m])

          A
358  1.4375
359  1.4375
360  1.5000
361  1.5000


Answered By - Ynjxsjmh
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing