只有在满足特定条件时,我才希望跳过数据帧输出的索引。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))
正如你所看到的,我会有很多记录,Panda会迭代数据,并为每个{ ... }
分配一个索引。3也会根据B值(即价格)进行排序,它会显示最低价格。
想要我想要的是一个检查,显示最低价格和卖家,只要类型是欧元(忽略所有类型为美元的记录)。。。我该怎么做?我尽力解释。。。谢谢
在线可编译示例:https://www.online-python.com/Bxj2OY3els
使用:
import pandas
Data= []
Data+=[{"A": "X1FFFFF", "Special":{"type": "USD"},"B": "0.11",}]
Data+=[{"A": "X2FFFFF", "Special":{"type": "EUR"},"B": "0.122",}]
Data+=[{"A": "X3FFFFF", "Special":{"type": "EUR"},"B": "0.1444",}]
#all data in Special are strings, simulate by astype(str)
Data = pandas.DataFrame(Data).astype(str)
Data = Data.astype({"B": float})
Data = Data.astype({"A": str})
import ast
#convert to dicts if necessary
Data["Special"] = Data["Special"].apply(ast.literal_eval)
#filtering `type` for `EUR`
euro_rows = Data.loc[Data["Special"].str.get('type') == 'EUR']
#get minimal value and index (A) by minimal
lowest_price = euro_rows.set_index('A')['B']
seller = lowest_price.idxmin()
price = lowest_price.min()
print(seller)
X2FFFFF
print(price)
0.122
我认为你可以这样做:
# 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
在过滤之前,最好使用pd.json_normalize
读取数据以获得所需信息:
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