首页 > 解决方案 > 从命令行运行.py文件但不在juypter笔记本中时np.random.permutation上的ValueError

问题描述

我正在运行以下代码

import pandas as pd
import numpy as np 
import tensorflow as tf

california_housing_dataframe = pd.read_csv("https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv", sep=",")

california_housing_dataframe = california_housing_dataframe.reindex(np.random.permutation(california_housing_dataframe))
california_housing_dataframe["median_house_value"] /= 1000.0
print(california_housing_dataframe.describe())
print(california_housing_dataframe)

这会导致 ValueError:

“ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()”

但是,相同的代码在 jupyter notebook 中运行(只需删除打印并直接调用数据框)。

我可以看到问题出在“np.random.permutation”行。如果我不这样做就打印数据框,它会打印得很好。但是为什么在 jupyter notebook 中运行它没有问题呢?而且,我该如何解决这个问题,以便我可以从命令行运行 .py 程序?

标签: pythonpandasnumpy

解决方案


代替:

california_housing_dataframe = california_housing_dataframe.reindex(np.random.permutation(california_housing_dataframe))

和:

california_housing_dataframe = california_housing_dataframe.reindex(np.random.permutation(california_housing_dataframe.index))

(将索引设置为数据帧的置换索引,而不是整个置换数据帧)


推荐阅读