python list - only keep only-positive or only-negative values
Using a list comprehension.
Ex:
l = [1, 2, 3, -1, -2, -5, 6, 7, -6]
print([i for i in set(l) if -i not in l])
Output:
[3, -5, 7]
How to sort only positive numbers from a list?
You have several issues:
- you have a variable that's named the same as a basic type (
list
), which shadows the type; pick a better name for i in range(my_list):
doesn't do what you think; you could dofor i in range(len(my_list)):
, but you can also justfor n in my_list:
andn
will be every element inmy_list
in turn- your user enters text, you'll need to turn those strings into integers before comparing them to other integers, using
int()
- you do
for i ..
but alsoi += 1
you don't need to increment the for-loop variable yourself.
Look into list comprehensions, they are perfect for what you're trying to do in a more complicated way, to construct positive_list
.
Your solution could be as simple as:
print(sorted([int(x) for x in input().split() if int(x) > 0]))
But staying closer to what you were trying:
numbers = [int(x) for x in input().split()]
sorted_positive_numbers = sorted([x for x in numbers if x > 0])
print(sorted_positive_numbers)
If you insist on a for
-loop instead of a list comprehension:
numbers = [int(x) for x in input().split()]
positive_numbers = []
for number in numbers:
if number > 0:
positive_numbers.append(number)
print(sorted(positive_numbers))
How to select rows with only positive or negative values in Pandas
You can use the OR (|
) to combine conditions:
print(df[(df[df.columns] >= 0).all(axis=1) | (df[df.columns] <= 0).all(axis=1)])
Prints:
x y z
1 2 3 1
2 3 2 5
5 -3 -2 -1
Or simpler:
print(df[(df >= 0).all(axis=1) | (df <= 0).all(axis=1)])
EDIT: As @Erfan stated in the comments, if you want strictly negative (without 0), you use <
:
print(df[(df >= 0).all(axis=1) | (df < 0).all(axis=1)])
Extract positive and negative values from an array in Python
The solution
Use two np.where
s to replace the values below zero and above zero:
>>> import numpy as np
>>> A = np.array([[-1, 2, -3], [4, -5, 6], [-7, 8, -9]])
>>> B = np.where(A > 0, A, 0)
>>> C = np.where(A < 0, A, 0)
>>> B
array([[0, 2, 0],
[4, 0, 6],
[0, 8, 0]])
>>> C
array([[-1, 0, -3],
[ 0, -5, 0],
[-7, 0, -9]])
The explanation
The three argument form of np.where
broadcasts the arguments, the first and second already have the same shape (3, 3)
but the 0
will be broadcasted to:
>>> Ag0_bc, B_bc, zero_bc = np.broadcast_arrays(A > 0, A, 0)
>>> Ag0_bc
array([[False, True, False],
[ True, False, True],
[False, True, False]], dtype=bool)
>>> zero_bc
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
Then np.where
will create a new array and fill each element in the new array with the corresponding element from the second argument (A
) if the element in the first argument (A > 0
) is True
and take the element from the third argument 0
in case it's False
.
Related Topics
Spliting a Row to Multiple Row Pyspark
Robot Framework Using Python, Key Press Without Selecting Any Button or Element in the Page
How to Delete a Column That Contains Only Zeros in Pandas
How to Prevent Brokenpipeerror When Doing a Flush in Python
Import Error: Dll Load Failed in Jupyter Notebook But Working in .Py File
How to Make Tkinter Frames in a Loop and Update Object Values
How to Concisely Replace Column Values Given Multiple Conditions
Change CSV Name to CSV Date Time Python
Get Usb Device Address Through Python
Python Turning 2 Dimensional Strings on My List into Floats
How to Make a Smiley Face in Turtle
Reading a CSV That Sometimes Contain Multiple Whitespaces
Numpy: How to Pick Rows from Two 2D Arrays Based on Conditions in 1D Arrays
How to Add an Attention Mechanism in Keras
How to Set Proxy for Chrome in Python Webdriver
Pandas Update and Add Rows One Dataframe With Key Column in Another Dataframe
How to Install Pypdf2 Module Using Windows
How to Make a Discord Bot Leave a Server from a Command in Another Server