Select a column in which all variable values meet the conditions in the cells

Viewed 82

Good day! I need help. I am studying pandas and I can't find the answer to my question.

Let's say I have a table where the last 3 rows may contain some conditions (for example '<= 0.1'):

t1_condition=pd. DataFrame({
0 : [0, 1, 1, None, None, None],
1 : [0, 0, 1, None, None, '<= 0.1'],
2 : [0, 0, 1, None, None, '> 0.1'],
3 : [0, 1, 0, '<= 35', '<= 2', None],
4 : [0, 1, 0, '<= 35', '> 2', '<= 0.1'],
}, index=['a', 'b', 'c', 'd', 'e', 'f'])

I have specific numeric values in my input (let's say: a=0, b=1, c=0, d=20, e=3, f=0.05) I need to select a column in which all the values of the variables meet the conditions in the cells (in this example, column 4). How to choose by matching for the first three rows (a, b, c) I figured out.

t1_condition = t1_condition. transpose () # changing columns to rows, and rows to columns
data_2 = t1_condition. loc[(t1_condition['a'] == a) & (t1_condition ['b'] == b) & (t1_condition['c'] == c)],

data_2-contains the column I need (but in the form of a string, I did transpose ()).

I can't figure out how, for example, to write an algorithm for comparing the value of the variable d. I guess so far:
1)take each value from the string d,
2)split by a space,
3) write the if/elif/else algorithm for each case (</>/<=/, etc.)
4)if the condition in the cell is satisfied, change the cell value to True, otherwise-to False.
5) search the modified table by matching with a specific value as for the first three rows.

Is there any more rational way to not write 1000500 lines for if/elif/else or for method description?

1 Answers

Your question is not particularly clear but I believe the below is what you are looking for. You should make use of the Python eval function to apply the condition strings as operators over elements of the df.

def op(x,o):
    if (o is None) or (o!=o):
        return True
    return eval(f'{x} {o}')

n_cols = len('abc')

t1_condition['result'] = t1_condition.apply(
    lambda x: \
        all([op(x.iloc[i], x.iloc[i+n_cols]) 
             for i in range(n_cols)]), 
    axis=1)
Related