首页 > 解决方案 > 熊猫数据框,如果条件满足则跳过索引

问题描述

我只想在满足特定条件时才跳过数据帧输出的索引。A这是卖家的特殊ID。B这是售价。类型是销售类型。

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))

如您所见,我将有很多记录,pandas 将迭代数据并为每个记录分配一个索引,{ ... }还将根据 B 值(即价格)进行排序,它将显示最低价格。

我想要一张支票来显示最低价格和卖家,只要类型是欧元(忽略所有类型为美元的记录)......我该怎么做?我试图尽可能地解释......谢谢。

在线编译示例: https ://www.online-python.com/Bxj2OY3els

标签: pythonpandas

解决方案


我认为你可以这样做:

# 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

推荐阅读