Python Forum
Interpreting this code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Interpreting this code
#2
The documentation for numpy.where()

https://numpy.org/doc/stable/reference/g...where.html

Quote:numpy.where
numpy.where(condition, [x, y, ]/)
Return elements chosen from x or y depending on condition.

Note

When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.

Parameters:
conditionarray_like, bool
Where True, yield x, otherwise yield y.

x, yarray_like
Values from which to choose. x, y and condition need to be broadcastable to some shape.

Returns:
outndarray
An array with elements from x where condition is True, and elements from y elsewhere.

This is your condition
intermediate3_df['CODE']=='LMU
This is "x"
intermediate3_df['thing1'].str.replace(" ","")
This is "y"
intermediate3_df['thing1'
If your condition is True (df["CODE"] == "LSU"), "where" will select x (with stri.replace), othewise it will select y (no str.replace).
A simple example:
import pandas as pd
import numpy as np

df = pd.DataFrame({"Numbers": range(1, 11)})
df["Even"] = np.where(df["Numbers"] % 2, None, df["Numbers"])
df["Odd"] = np.where(df["Numbers"] % 2, df["Numbers"], None)
print(df)
Output:
Numbers Even Odd 0 1 None 1 1 2 2 None 2 3 None 3 3 4 4 None 4 5 None 5 5 6 6 None 6 7 None 7 7 8 8 None 8 9 None 9 9 10 10 None
Reply


Messages In This Thread
Interpreting this code - by EmBeck87 - Apr-07-2023, 04:36 PM
RE: Interpreting this code - by deanhystad - Apr-07-2023, 07:47 PM
RE: Interpreting this code - by EmBeck87 - Apr-07-2023, 07:48 PM
RE: Interpreting this code - by deanhystad - Apr-07-2023, 08:32 PM
RE: Interpreting this code - by EmBeck87 - Apr-10-2023, 12:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Trouble interpreting prime number code ryfoa6 1 2,305 Mar-20-2020, 03:47 PM
Last Post: stullis
  Help interpreting code schniefen 1 2,108 May-03-2019, 05:23 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020