Верните метку индекса, если какое-либо условие выполняется для столбца в Pandas Dataframe
Учитывая Dataframe, верните все те индексные метки, для которых выполняется какое-либо условие для определенного столбца.
Solution #1: We can use simple indexing operation to select all those values in the column which satisfies the given condition.
# importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({"Date":["10/2/2011", "11/2/2011", "12/2/2011", "13/2/2011"], "Product":["Umbrella", "Matress", "Badminton", "Shuttle"], "Last_Price":[1200, 1500, 1600, 352], "Updated_Price":[1250, 1450, 1550, 400], "Discount":[10, 10, 10, 10]}) # Create the indexesdf.index =["Item 1", "Item 2", "Item 3", "Item 4"] # Print the dataframeprint(df) |
Выход :

Теперь мы хотим узнать индексные метки всех элементов, у которых 'Updated_Price' больше 1000.
# Select all the rows which satisfies the criteria# convert the collection of index labels to list.Index_label = df[df["Updated Price"]>1000].index.tolist() # Print all the labelsprint(Index_label) |
Output :
As we can see in the output, the above operation has successfully evaluated all the values and has returned a list containing the index labels.
Solution #2: We can use Pandas Dataframe.query() function to select all the rows which satisfies some condition over a given column.
# importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({"Date":["10/2/2011", "11/2/2011", "12/2/2011", "13/2/2011"], "Product":["Umbrella", "Matress", "Badminton", "Shuttle"], "Last_Price":[1200, 1500, 1600, 352], "Updated_Price":[1250, 1450, 1550, 400], "Discount":[10, 10, 10, 10]}) # Create the indexesdf.index =["Item 1", "Item 2", "Item 3", "Item 4"] # Print the dataframeprint(df) |
Выход :
Now, we want to find out the index labels of all items whose ‘Updated_Price’ is greater than 1000.
# Select all the rows which satisfies the criteria# convert the collection of index labels to list.Index_label = df.query("Updated_Price > 1000").index.tolist() # Print all the labelsprint(Index_label) |
Выход :
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.