【问题标题】:TypeError: only size-1 arrays can be converted to Python scalars,TypeError: 只有大小为 1 的数组可以转换为 Python 标量,
【发布时间】:2021-10-17 09:17:42
【问题描述】:

我正在尝试打印一个包含 5 列的 df,其中包含有关金融工具的一些信息。 列表no_float_prezzo 是在解析网络时创建的,它包含text data。 要创建第五列(损益列),我需要对列表 quantitàinvestimentono_float_prezzo 进行一些算术运算。 但是我不能做这个算术运算,因为 Python 不能将 no_float_prezzo 文本数据转换成浮点数。

我尝试做prezzo = float(no_float_prezzo),但终端给了我错误:"TypeError: only size-1 arrays can be converted to Python scalars"

代码如下:

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

import time

import pandas as pd

import numpy as np


[...]

################## DATAFRAME #################

asset = ['BTC/EUR', 'Eurostoxx select dividend 30', 'ESPO', 'AcomeA Eurobbligazionario']

***no_float_prezzo = np.array([BTCEUR_price, EUROSTOXXSELECTDIVIDEND30price, ESPOprice, ACOMEAEUROBBprice])***

*prezzo = float(no_float_prezzo)*

quantità = np.array([0.00717041, 48, 28, 32.388], dtype=np.float64)

investimento = np.array([296.4, 1002.24, 986.16, 725], dtype=np.float64)

profit_loss_perc = ((quantità*prezzo-investimento)/investimento)

col = ['asset', 'prezzo', 'quantità', 'investimento']

pd.set_option("display.precision", 8)

df = pd.DataFrame({'asset': asset, 'prezzo': prezzo, 'quantità': quantità, 'investimento': investimento})


print(df.to_string(index=False))

我也尝试了np.vectorize,但没有。

【问题讨论】:

  • 你有没有花时间查找pythonfloat函数?

标签: python pandas numpy selenium


【解决方案1】:

尝试使用 Numpy astype(dtype) 函数,因为 Python 内置的 float 函数只接受标量值。

import numpy as np

BTCEUR_price = '-134.56'
EUROSTOXXSELECTDIVIDEND30price = '1.34e2'
ESPOprice = '-193.9e-2'
ACOMEAEUROBBprice = '+843.059485'

no_float_prezzo = np.array([BTCEUR_price, EUROSTOXXSELECTDIVIDEND30price, ESPOprice, ACOMEAEUROBBprice])

prezzo = no_float_prezzo.astype(np.float64)

quantità = np.array([0.00717041, 48, 28, 32.388], dtype=np.float64)
investimento = np.array([296.4, 1002.24, 986.16, 725], dtype=np.float64)
profit_loss_perc = ((quantità*prezzo-investimento)/investimento)

print(profit_loss_perc)
[-1.00325523  5.41762452 -1.05505395 36.66208359]

【讨论】:

    猜你喜欢
    • 2018-07-22
    • 2021-06-24
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    • 2019-06-19
    • 2020-08-09
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多