无法将numpy数组分配给pandas数据框

时间:2020-06-03 20:21:08

标签: python python-3.x numpy

我无法将numpy数组的元组中的numpy数组分配给熊猫数据帧。有人能帮我吗?我正在使用第三方库来获取数据并生成输出numpy数组。

代码:

import time

import numpy as np
import pandas as pd

import ccxt # crypto exchange library
import tulipy as ti # financial indicators

def currentTimeMillis(self):
    return int(round(time.time() * 1000))

currentMillisMinus250min  = currentTimeMillis() - 30000000

bitmex = ccxt.bitmex()

ohlcvDf = pd.DataFrame(
            bitmex.fetch_ohlcv(symbol="BTC/USD", limit=500, timeframe="1m", since=currentMillisMinus250min),
            columns = ["timestamp", "open", "high", "low", "close", "volume"])

macdNp = ti.macd(ohlcvDf["close"].to_numpy(), 12, 26, 9)

ohlcvDf["macd"] = macdNp[0]
ohlcvDf["signal"] = macdNp[1]

错误:

ValueError: Length of values does not match length of index

ndarrays元组:

(
 array([ 6.68695914e+00,  6.12108219e+00,  5.64479926e+00,  4.94431782e+00,
         4.33794071e+00,  3.81237487e+00,  3.46875952e+00,  3.15956840e+00]), 
 array([ 6.68695914,   6.57378375,   6.38798685,   6.09925304,
         5.74699058,   5.36006744,   4.98180585,   4.61735836]),
 array([ 0.00000000e+00, -4.52701560e-01, -7.43187590e-01, -1.15493523e+00,
        -1.40904987e+00, -1.54769256e+00, -1.51304634e+00, -1.45778996e+00])
)

2 个答案:

答案 0 :(得分:1)

import time

import numpy as np
import pandas as pd

import ccxt # crypto exchange library
import tulipy as ti # financial indicators

def currentTimeMillis():
    return int(round(time.time() * 1000))

currentMillisMinus250min  = currentTimeMillis() - 30000000

bitmex = ccxt.bitmex()

ohlcvDf = pd.DataFrame(
        bitmex.fetch_ohlcv(symbol="BTC/USD", limit=500, timeframe="1m", since=currentMillisMinus250min),
        columns = ["timestamp", "open", "high", "low", "close", "volume"])

macdNp = ti.macd(ohlcvDf["close"].to_numpy(), 12, 26, 9)

nan_arr = np.nan * np.ones(shape=(25,))
ohlcvDf["macd"] = np.append(nan_arr, macdNp[0])
ohlcvDf["signal"] = np.append(nan_arr, macdNp[1])

在您的代码中,您使用了 self,self.macdPeriodFast,self.macdPeriodSlow,self.macdSignal ,但没有在任何地方引用它,因为我只是阅读了这些库并试图生成元组(可能与您的不一样)。但是我能够生成元组并打印这些数组。

您能否提供在此特定代码中使用的其他任何内容!

我已经阅读了关于图书馆here

的信息

答案 1 :(得分:-2)

更好的方法是使用np.array而不是array。

import numpy as np

arrays = (
 np.array([ 6.68695914e+00,  6.12108219e+00,  5.64479926e+00,  4.94431782e+00,
         4.33794071e+00,  3.81237487e+00,  3.46875952e+00,  3.15956840e+00]), 
 np.array([ 6.68695914,   6.57378375,   6.38798685,   6.09925304,
         5.74699058,   5.36006744,   4.98180585,   4.61735836]),
 np.array([ 0.00000000e+00, -4.52701560e-01, -7.43187590e-01, -1.15493523e+00,
        -1.40904987e+00, -1.54769256e+00, -1.51304634e+00, -1.45778996e+00])
)

print(arrays[0])

输出:

[6.68695914 6.12108219 5.64479926 4.94431782 4.33794071 3.81237487
 3.46875952 3.1595684 ]