Reputation: 1
I have a dataframe that contain some data. I want to apply a condition on this dataframe.
When i wrote the code like this:-
import pandas as pd
data_store = pd.read_excel("101010.xlsx")
fff = data_store[data_store.Price > 20]
print(fff.sort_values("Total Sale", ascending=False))
The program is running and return(show) dataframe elements value as i want like this:-
Total Sale Price
100000 64
95000 21
94000 25
70000 30
61000 41
59000 23
54000 50
40000 55
But when i wrote that code in single line like this:-
import pandas as pd
data_store = pd.read_excel("101010.xlsx")
fff = (data_store[data_store.Price > 20]) and (data_store.sort_values("Total Sale", ascending=False))
print(fff)
I get error like this:-
Traceback (most recent call last):
File "C:/Users/Moli/PycharmProjects/first/main.py", line 3, in <module>
fff = (data_store[data_store.Price > 20]) and (data_store.sort_values("Total Sale",
ascending=False))
File "C:\Python37\lib\site-packages\pandas\core\generic.py", line 1327, in __nonzero__
f"The truth value of a {type(self).__name__} is ambiguous. "
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any()
or a.all().
Process finished with exit code 1
Please can some body help me. How i can write this condition in single line like this:-
(data_store[data_store.Price > 20]) and (data_store.sort_values("Total Sale", ascending=False))
Thank you in advance :) :) :)
Upvotes: 0
Views: 57
Reputation: 5286
and
is a logical and, it compares the previous and next statements, evaluate them to booleans and perform a logical and.
Your previous and next statemens are:
data_store[data_store.Price > 20]
data_store.sort_values("Total Sale", ascending=False)
Both return a dataframe (filtered by price) so basically you are trying to do a logical and operation to two dataframes. As the error reports, a dataframe doesn't have a boolean value, it is ambiguous.
So summing up, and
does not concatenate the actions, it performs a logical and, which breaks before dataframes can't be converted to boolean values.
What you want to do, as @ShivamJha pointed out in a comment, is the following:
import pandas as pd
data_store = pd.read_excel("101010.xlsx")
fff = data_store[data_store.Price > 20].sort_values("Total Sale", ascending=False)
print(fff)
Upvotes: 1