how do i get np.where to accept more arguments, so it will filter >, < , and =; not just > and <?

  • Last Update :
  • Techknowledgy :

I want to change it to - if df.PofChg is > 0, if true display "Up" or if false display "Down", but if it is equal to zero then Display "Flat"

np.where(df.PofChg > 0, 'Up', np.where(df.PofChg == 0, 'Flat', 'Down'))

I would use map() in conjunction with np.sign() in this case:

In[133]: mp = {
   -1: 'Down',
   0: 'Flat',
   1: 'Up'
}

In[134]: df['U_D_F'] = np.sign(df.PofChg).map(mp)

In[135]: df
Out[135]:
   PofChg U_D_F
0 - 1 Down
1 0 Flat
2 1 Up
3 - 2 Down
4 0 Flat
5 5 Up
6 3 Up
7 - 6 Down

np.sign():

In[136]: np.sign(df.PofChg)
Out[136]:
   0 - 1
1 0
2 1
3 - 1
4 0
5 1
6 1
7 - 1
Name: PofChg, dtype: int64

Type of np.sign(df.PofChg):

In[9]: type(np.sign(df.PofChg))
Out[9]: pandas.core.series.Series

Suggestion : 2

How do I get np.where to accept more arguments, so it will filter >, < , and =; not just > and <?,How to compare two dataframes and filter rows and columns where a difference is found,How do I create a function that will accept a pandas dataframe and remove rows containing a specific value?,How do I get the x and y labels to appear when displaying more then one histogram using pandas hist() function with the by argument?

I want to change it to - if df.PofChg is > 0, if true display "Up" or if false display "Down", but if it is equal to zero then Display "Flat"

np.where(df.PofChg > 0, 'Up', np.where(df.PofChg == 0, 'Flat', 'Down'))

I would use map() in conjunction with np.sign() in this case:

In[133]: mp = {
   -1: 'Down',
   0: 'Flat',
   1: 'Up'
}

In[134]: df['U_D_F'] = np.sign(df.PofChg).map(mp)

In[135]: df
Out[135]:
   PofChg U_D_F
0 - 1 Down
1 0 Flat
2 1 Up
3 - 2 Down
4 0 Flat
5 5 Up
6 3 Up
7 - 6 Down

np.sign():

In[136]: np.sign(df.PofChg)
Out[136]:
   0 - 1
1 0
2 1
3 - 1
4 0
5 1
6 1
7 - 1
Name: PofChg, dtype: int64

Type of np.sign(df.PofChg):

In[9]: type(np.sign(df.PofChg))
Out[9]: pandas.core.series.Series

Suggestion : 3

Use np.where() to select indexes of elements that satisfy multiple conditions,In the previous example we used a single condition in the np.where(), but we can use multiple conditions too inside the numpy.where(). For example,,Using numpy.where() without condition expression,Now we want to find the indexes of elements in this array that satisfy our given condition i.e. element should be greater than 12 but less than 16. For this we can use the np.where() by passing the condition argument only i.e.

Syntax of np.where()

numpy.where(condition[, x, y])

Suppose we have a numpy array and two lists of the same size,

arr = np.array([11, 12, 13, 14])

high_values = ['High', 'High', 'High', 'High']
low_values = ['Low', 'Low', 'Low', 'Low']

Now we want to convert this Numpy array arr to another array of the same size, where it will contain the values from lists high_values and low_values. Like, if the value in arr is greater than 12 then replace it with the corresponding value from high_values i.e ‘High’. Whereas, if the value in arr is less then 12 then replace it with the corresponding value in low_values i.e. ‘Low’. So, our new numpy array should be like this,

['Low'
   'Low'
   'High'
   'High'
]

Output:

['Low'
   'Low'
   'High'
   'High'
]

We passed the three arguments in the np.where(). The first argument is the condition on the numpy array arr which got converted to a bool array i.e.

arr > 12 == > [False False True True]

Suggestion : 4

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.,An array with elements from x where condition is True, and elements from y elsewhere.,The function that is called when x and y are omitted,The shapes of x, y, and the condition are broadcast together:

[xv
   if c
   else yv
   for c, xv, yv in zip(condition, x, y)
]
>>> a = np.arange(10) >>>
   a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>>
   np.where(a < 5, a, 10 * a)
array([0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
>>> np.where([
      [True, False],
      [True, True]
   ],
   ...[
      [1, 2],
      [3, 4]
   ],
   ...[
      [9, 8],
      [7, 6]
   ])
array([
   [1, 8],
   [3, 4]
])
>>> x, y = np.ogrid[: 3,: 4] >>>
   np.where(x < y, x, 10 + y) # both x and 10 + y are broadcast
array([
   [10, 0, 0, 0],
   [10, 11, 1, 1],
   [10, 11, 12, 2]
])
>>> a = np.array([
      [0, 1, 2],
      ...[0, 2, 4],
      ...[0, 3, 6]
   ]) >>>
   np.where(a < 4, a, -1) # - 1 is broadcast
array([
   [0, 1, 2],
   [0, 2, -1],
   [0, 3, -1]
])

Suggestion : 5

Different data-types allow us to store data more compactly in memory, but most of the time we simply work with floating point numbers. Note that, in the example above, NumPy auto-detects the data-type from the input.,The recommended convention to import numpy is:,Follow-up: Move the above code into a script file named prime_sieve.py Run it to check it works Use the optimization suggested in the sieve of Eratosthenes: Skip j which are already known to not be primes The first number to cross out is ,A slicing operation creates a view on the original array, which is just a way of accessing array data. Thus the original array is not copied in memory. You can use np.may_share_memory() to check if two arrays share the same memory block. Note however, that this uses heuristics and may give you false positives.

>>>
import numpy as np
   >>>
   a = np.array([0, 1, 2, 3]) >>>
   a
array([0, 1, 2, 3])
In[1]: L = range(1000)

In[2]: % timeit[i ** 2
   for i in L]
1000 loops, best of 3: 403 us per loop

In[3]: a = np.arange(1000)

In[4]: % timeit a ** 2
100000 loops, best of 3: 12.7 us per loop
In [5]: np.array?
String Form:<built-in function array>
   Docstring:
   array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0, ...
>>> np.lookfor('create array')
Search results
for 'create array'
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
numpy.array
Create an array.
numpy.memmap
Create a memory - map to an array stored in a * binary * file on disk.
In[6]: np.con * ?
   np.concatenate
np.conj
np.conjugate
np.convolve
>>>
import numpy as np

Suggestion : 6

Most stream operations accept parameters that describe user-specified behavior, such as the lambda expression w -> w.getWeight() passed to mapToInt in the example above. To preserve correct behavior, these behavioral parameters: ,Such parameters are always instances of a functional interface such as Function, and are often lambda expressions or method references. Unless otherwise specified these parameters must be non-null. ,For parallel stream pipelines, the action may be called at whatever time and in whatever thread the element is made available by the upstream operation. If the action modifies shared state, it is responsible for providing the required synchronization., Nested Class Summary Nested Classes  Modifier and Type Interface and Description static interface  Stream.Builder<T> A mutable builder for a Stream.


public interface Stream<T>
   extends BaseStream<T,Stream<T>>
int sum = widgets.stream()
   .filter(w - > w.getColor() == RED)
   .mapToInt(w - > w.getWeight())
   .sum();
int sum = widgets.stream()
   .filter(w - > w.getColor() == RED)
   .mapToInt(w - > w.getWeight())
   .sum();

filter

Stream<T> filter(Predicate<? super T> predicate)

map

<R> Stream<R> map(Function<? super T,? extends R> mapper)

mapToInt

IntStream mapToInt(ToIntFunction < ? super T > mapper)

mapToLong

LongStream mapToLong(ToLongFunction < ? super T > mapper)