I have a dataframe which select lowest price and seller from an json. However sometimes i get this error: ValueError: can only convert an array of size 1 to a Python scalar
it happens just sometimes, not always.
Here is the code..
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",}]
Data = pandas.DataFrame(Data)
Data = Data.astype({"B": float})
Data = Data.astype({"A": str})
euro_rows = Data.loc[Data["Special"] == {'type': 'EUR'}]
lowest_price = euro_rows.loc[euro_rows['B'] == euro_rows['B'].min()]
seller = lowest_price['A'].item()
price = lowest_price['B'].item()
print(seller)
print(price)
what i can do to fix that error?
Full error :
File "Fuck.py", line 50, in GetLowestPriceAndSeller
seller = lowest_price['seller'].item()
File "/usr/local/lib/python3.8/site-packages/pandas/core/base.py", line 420, in item
raise ValueError("can only convert an array of size 1 to a Python scalar")
ValueError: can only convert an array of size 1 to a Python scalar
CodePudding user response:
My guess is, that you have several items in lowest_price, which might be possible if they cost exactly the same, which would also explain, why it is only happening sometimes.
So the culprit is probably the call to .item(), which expects a single item, but you have an array in there.
You could then simple take the whole lowest_price array instead of just the item. This depends a bit on what you exactly want to do with the data, because in my opinion the circumstances change a bit from what you originally had.
CodePudding user response:
You can select first value if always exist at least one value:
seller = lowest_price['A'].iat[0]
price = lowest_price['B'].iat[0]
If possible sometimes first value not exist, because lowest_price
is empty is possible use this trick for specify default value with iter
with next
:
seller = next(iter(lowest_price['A']), 'default')
price = next(iter(lowest_price['B']), 'default')
Alternative solution is convert A
to index and then get minimal of B
and index (A
) by minimal value by Series.idxmin
:
lowest_price = euro_rows.set_index('A')['B']
seller = lowest_price.idxmin()
price = lowest_price.min()
print(seller)
print(price)