Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new column based on index of values in another sorted list

Tags:

I have a dataframe in pandas

val1 val2 val3 time 
 a    b    c    0       
 d    e    f    5
 g    h    i    7
 j    k    l    4
 c    a    q    9
 m    e    t    2
 g    n    y    1
 v    k    l    0

and timesteps = [0, 3, 8]

And I want to create a new column that is the the maximal value of an elemet from timesteps that is lower than row["time"] For example, here the new column will be [0,3,3,3,8,0,0,0]

What is the best way to do so?

like image 283
or_aug Avatar asked Jun 05 '19 06:06

or_aug


People also ask

How do you create a new column based on values from other columns in pandas?

Using apply() method If you need to apply a method over an existing column in order to compute some values that will eventually be added as a new column in the existing DataFrame, then pandas. DataFrame. apply() method should do the trick.

How do I filter a column based on another column in pandas?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression. The blow example returns a Courses column where the Fee column value matches with 25000.

How do I change the index of a DataFrame to another column?

You can change the index to a different column by using set_index() after reset_index() .


1 Answers

Using pd.cut():

timesteps = [0, 3, 8]
bins=timesteps+[df.time.max()]
#[0, 3, 8, 9]
pd.cut(df.time,bins=bins,labels=timesteps,include_lowest=True)

0    0
1    3
2    3
3    3
4    8
5    0
6    0
7    0
like image 50
anky Avatar answered Sep 23 '22 23:09

anky