Home > Back-end >  Select columns in pyrhon based on a condition
Select columns in pyrhon based on a condition

Time:05-17

I am new to Python!

I have an input vector of p. I am trying to select columns of p such that p(i)>2 and put them into a new vector y. e.g. something like below which by the way, gives error:

y=(p[i]>2)

CodePudding user response:

If I understand correctly, your question is not about Pandas Dataframe, rather about regular Python List. If so, you can use list comprehension.

A list comprehension is a short syntax for iterating through a list and picking the elements that satisfy a certain condition.

Let's see first how you can accomplish what you want with a regular for loop (the non-pythonic way):

my_list = [1, 4, 6, 1, 0]
my_new_list = []
for n in my_list:
    if n > 2:
        my_new_list.append(n)

Now, Python makes such a selection of elements from a list very easy using the list comprehension syntax:

my_new_list = [n for n in my_list if n > 2]

where the first n refers to what we append to my_new_list, then comes the for loop and finally the filtering condition.

CodePudding user response:

In python you have to select give the column name value inside the bracket so you need to give the column name first and then you will be able to acces that column and then condition will be working fine. LIke this:

y = dataframe[p['i'] > 80]

and also you will be getting a column which will be taken as dataframe. visit this website for more information.

  • Related