I would like to know if there is a faster and more “pythonic” way to do the following, for example. using some built-in methods. Given a pandas DataFrame or numpy array for float, if the value is equal to or less than 0.5, I need to calculate the inverse value and multiply by -1 and replace the old value with the newly calculated one. "Transformation" is probably a poor choice of words, please tell me if you have a better / more accurate description.
Thanks for the help and support!
Data:
import numpy as np
import pandas as pd
dicti = {"A" : np.arange(0.0, 3, 0.1),
"B" : np.arange(0, 30, 1),
"C" : list("ELVISLIVES")*3}
df = pd.DataFrame(dicti)
my function:
def transform_colname(df, colname):
series = df[colname]
newval_list = []
for val in series:
if val <= 0.5:
newval = (1/val)*-1
newval_list.append(newval)
else:
newval_list.append(val)
df[colname] = newval_list
return df
function call:
transform_colname(df, colname="A")
** → I am summarizing the results here, since the comments do not allow sending the code (or I do not know how to do this). **
Thank you all for your quick and excellent answers!
ipython "% timeit" "" :
:
10, 3: 24,1
jojo:
def transform_colname_v2(df, colname):
series = df[colname]
df[colname] = np.where(series <= 0.5, 1/series*-1, series)
return df
100 , 3: 2,76
FooBar:
def transform_colname_v3(df, colname):
df.loc[df[colname] <= 0.5, colname] = - 1 / df[colname][df[colname] <= 0.5]
return df
100 , 3: 3,32
dmvianna:
def transform_colname_v4(df, colname):
df[colname] = df[colname].where(df[colname] <= 0.5, (1/df[colname])*-1)
return df
100 , 3: 3,7
/ , -!
: ()
"FooBar" "dmvianna" ""? , ( ). , !
- > jojo, ".loc" - , df [colname]. "". ( " > " "< =" )
!