将numpy数组转换为元组会弄乱里面的值

时间:2018-12-19 12:34:58

标签: python pandas

当我尝试将numpy数组转换为元组时,发生了一些奇怪的事情。

代码:

data_block = np.append(training_values, target_value)  # merge
print('data_block: ', data_block)
data_block = tuple(data_block)
print('data_block tuple: ', data_block)

输出:

data_block:  [ 0.03478261  0.00869565  0.03478261  0.07826087  0.05217391  0.07826087 0.14782609]
data_block tuple:  (0.034782608695652174, 0.0086956521739130436, 0.034782608695652174, 0.078260869565217397, 0.052173913043478258, 0.078260869565217397, 0.14782608695652172)

有人可以向我解释发生了什么事吗?

这是功能的一部分,该功能试图创建可用于时间序列以外的监督学习的数据。目标是创建一个熊猫数据框。该函数本身尚未完成并包含错误,但我想在此处发布以获取更多上下文。

def series_to_supervised(data_list, look_back=1, look_forward=0):
print(look_back)
data, labels = [], []
for i in range(len(data_list) - look_back):
    training_values = data_list[i:(i + look_back)]  
    target_value = data_list[i + look_back + look_forward]  
    print('target_value: ', target_value)

    data_block = np.append(training_values, target_value)  # merge
    data_block = tuple(data_block)
    data = np.append(data, data_block)  # add to data as tuple

for i in range(look_back):
    labels.append("lb_" + str(i))
labels.append("target_value")
print(labels)

df = pandas.DataFrame(data=data)
return df

1 个答案:

答案 0 :(得分:1)

您为data_blocktuple(data_block)显示的值实际上匹配。 Numpy数组的打印与Python中的其他大多数东西有些不同,因此print语句的输出看起来有些不同。

您可以使打印输出匹配,如下所示:

with np.printoptions(precision=20, linewidth=9999):
    print(data_block)
print(tuple(data_block))

输出:

[0.034782608695652174 0.008695652173913044 0.034782608695652174 0.0782608695652174   0.05217391304347826  0.0782608695652174   0.14782608695652172 ]
(0.034782608695652174, 0.008695652173913044, 0.034782608695652174, 0.0782608695652174, 0.05217391304347826, 0.0782608695652174, 0.14782608695652172)

如果您一直希望您的numpy数组以这种高精度进行打印(您可能实际上并不希望这样做;它会很快使人烦恼),则可以在脚本中设置全局选项,如下所示:

np.set_printoptions(precision=20)