Home > OS >  pandas dataframe, skip index if condition is meet
pandas dataframe, skip index if condition is meet

Time:09-30

I want to skip the index of a data frame output only if specific conditions are met. A it's a special id for seller. B it's the selling price. Type is selling type.

import pandas

Data= []
Data =[{"A": "ID_1", "Special":{"type": "USD"},"B": "0.11",}]
Data =[{"A": "ID_2", "Special":{"type": "EUR"},"B": "0.122",}]
Data =[{"A": "ID_3", "Special":{"type": "EUR"},"B": "0.1444",}]

Data = pandas.DataFrame(Data)
Data = Data.sort_values(by=['B'], ascending=False)

seller = Data['A'][Data.index[-1]]
price  = Data['B'][Data.index[-1]]

print('{} {}'.format(seller, price))

As you can see, I will have many records, pandas will iterate data and assign an index for each { ... } also will be sorted based on B value which is price, it will display the lowest price.

Want I want is a check to display the lowest price AND seller just if the type is EUR (Ignore all records that have type USD)... How I can do that? I tried to explain as well as I can... Thanks.

Online compileable example: https://www.online-python.com/Bxj2OY3els

CodePudding user response:

I think you can do something like this:

# gets only the Euro type
euro_rows = Data.loc[Data["Special"] == {'type': 'EUR'}]

# gets the row of the lowest price
lowest_price = euro_rows.loc[euro_rows['B'] == euro_rows['B'].min()]

# gets seller and price
seller, price = lowest_price['A'].item(), lowest_price['B'].item()

print(seller) #prints: IDDDDDDDDDDD
print(price)  #prints: 0.1

CodePudding user response:

It might be better for you to read your data using pd.json_normalize before filtering to get what you need:

df = pd.json_normalize(Data).astype({"B": float})

#to get the row with the lowest price
>>> df[df["Special.type"]=="EUR"].nsmallest(1, "B")
      A      B Special.type
1  ID_2  0.122          EUR
  • Related