str(recent_prices.loc[0, [“itemPrice”]]) これを数値として返したい。

2024年6月25日

str(recent_prices.loc[0, ["itemPrice"]]) は文字列として返されるため、数値だけを返すためには .values を使って値を取り出すことができます。以下は修正したコードです:

python
def get_own_shop_prices(own_shop_code):
    # 最新の30件の商品を取得(更新日で降順にソート)

    # モデルのカラム名を取得
    columns = [field.name for field in RakutenItem._meta.fields]

    # モデルからデータを全件取得
    recent_items = RakutenItem.objects.order_by('-updated_at')[:30]
    

    # DataFrame に変換
    data = [{column: getattr(item, column) for column in columns} for item in recent_items]
    df = pd.DataFrame.from_records(data)
    # shopCode が特定の値の行を抽出
    recent_prices = df[df['shopCode'] == own_shop_code]
    
    # recent_prices が空でない場合
    if not recent_prices.empty:
        recent_prices = recent_prices.sort_values(by='itemPrice', ascending=True)
        recent_prices = recent_prices.reset_index(drop=True)
        print(";" * 20)
        print(recent_prices.loc[0, ["itemPrice"]])
        data = recent_prices.loc[0, ["itemPrice"]].values[0]
        return data
    else:
        print("No data available")
        return None

この修正により、data には数値が入るようになります。

未分類

Posted by ぼっち