Skip to content

Instantly share code, notes, and snippets.

%%time
# apply, but pre-select columns e and f instead of complete rows: iteration misdemeanor
def myfunc4(b, c):
x = (b + c)**2
y = (b - c)**2
z = (b - c)**2
return x, y,z
dfY = pd.DataFrame()
%%time
# apply row-wise: iteration crime
def myfunc3(row):
return pd.Series(myfunc2(row))
dfY = pd.DataFrame()
dfY[["x", "y", "z"]] = dfS.apply(myfunc3, axis=1)
display(dfY.tail())
%%time
# convert df to dictionary before iterating
dictS = dfS.to_dict(orient="records")
for row in dictS:
res = myfunc2a(row)
dfY = pd.DataFrame.from_dict(dictY).T
dfY.columns = ["x", "y", "z"]
display(dfY.tail())
def myfunc2a(row):
x = (row["B"] + row["C"])**2
y = (row["B"] - row["C"])**2
z = (row["B"] - row["C"])**2
return [x, y,z]
%%time
# itertuples: iteration misdemeanor
dictY = dict()
for row in dfS.itertuples():
res = myfunc2(row)
dictY[row] = list(res)
dfY = pd.DataFrame.from_dict(dictY).T
dfY.columns = ["x", "y", "z"]
%%time
# iterrows: iteration felony
dictY = dict()
for i, row in dfS.iterrows():
res = myfunc2(row)
dictY[row.name] = list(res)
dfY = pd.DataFrame.from_dict(dictY).T
dfY.columns = ["x", "y", "z"]
def myfunc2(row):
x = (row.B + row.C)**2
y = (row.B - row.C)**2
z = (row.B - row.C)**2
return [x, y,z]
%%time
# conventional loop using iloc - iteration crime
dfY = pd.DataFrame()
for i in range(dfS.shape[0]):
res = myfunc1(dfS["B"].iloc[i], dfS["C"].iloc[i])
dfY = pd.concat([dfY, pd.DataFrame([res])], ignore_index=True)
dfY.rename(columns={0:"x", 1:"y", 2:"z"}, inplace=True)
display(dfY.tail())
def myfunc1(b, c):
x = (b + c)**2
y = (b - c)**2
z = (b - c)**2
return [x,y,z]
@h3ik0th
h3ik0th / vec_002
Last active October 6, 2022 15:04
def myfunc0(b, c):
r = np.sqrt(np.mean((b - c)**2))
return r
def variants(df, dftype):
dfX = df.copy()
print(dftype)
%timeit dfX["r1"] = (((dfX["B"] - dfX["C"])**2).mean())**0.5
%timeit dfX["r2"] = np.sqrt( np.mean((dfX["B"] - dfX["C"])**2))