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?
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.
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.
You can change the index to a different column by using set_index() after reset_index() .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With