python - 为什么我得到 : "Length of values does not match length of index" error?

标签 python pandas

我有以下代码,我正在尝试将 True 分配给一个新列,其中实际日期等于“D”列中的日期(创建日期)和 False 给任何其他人。

我是 Python 的新手,所以我想了解我做错了什么:

def GetData():
    myList = GetFileList(TodaysDate,5)
    NewDataFrame  = pd.DataFrame()
    for x in myList:
        #The date of the actuals data is the day BEFORE it was created  
        ActualDate = getDate(x) - timedelta(days=1)

        myTempData = pd.read_csv(WSIWeatherDir + "\\" + x, parse_dates = [" date"], date_parser = DateTimeParser)

        myTempData = myTempData.replace(-99,np.nan)
        myTempData = myTempData.loc[myTempData['name'].isin(NL_WeatherStations)]
        myTempData['D'] = myTempData[' date'].dt.date

        #MyData = myTempData.sort([' date'], ascending=True)
        #print MyData

        #Select indices of the weather file where the column " date" is equal to the actual date we are looking for
        MyActualIndex = myTempData['D'] == ActualDate
        MyActualData = myTempData[MyActualIndex]


        MyExpectedIndex = myTempData.index.difference(MyActualData.index)
        MyExpectedData =  myTempData.loc[MyExpectedIndex] 

        myTempData ['Actuals'] = [True] * len(MyActualData.index)
        myTempData ['Actuals'] = [False] * len(MyExpectedData.index)

        NewDataFrame = pd.concat([NewDataFrame,myTempData])
    return NewDataFrame
print GetData()

错误

runfile('C:/Users//Desktop/NLG_TAC_Calculation/TAC_2.py', wdir='C:/Users//Desktop/NLG_TAC_Calculation')
Traceback (most recent call last):

  File "<ipython-input-4-c9c151bca95a>", line 1, in <module>
    runfile('C:/Users//Desktop/NLG_TAC_Calculation/TAC_2.py', wdir='C:/Users//Desktop/NLG_TAC_Calculation')

  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
    execfile(filename, namespace)

  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users//Desktop/NLG_TAC_Calculation/TAC_2.py", line 117, in <module>
    print GetData()

  File "C:/Users//Desktop/NLG_TAC_Calculation/TAC_2.py", line 108, in GetData
    myTempData ['Actuals'] = [True] * len(MyActualData.index)

  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 2127, in __setitem__
    self._set_item(key, value)

  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 2204, in _set_item
    value = self._sanitize_column(key, value)

  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 2362, in _sanitize_column
    value = _sanitize_index(value, self.index, copy=False)

  File "C:\Python27\lib\site-packages\pandas\core\series.py", line 2579, in _sanitize_index
    raise ValueError('Length of values does not match length of '

ValueError: Length of values does not match length of index

最佳答案

我最好的猜测依赖于这部分:

myTempData ['Actuals'] = [True] * len(MyActualData.index)
myTempData ['Actuals'] = [False] * len(MyExpectedData.index)

它首先表示 myTempData['Actuals'] 是一个大小为 len(MyActualData.index) 的列,仅包含 True 值。接下来,它用包含 False 值的另一列大小 len(MyExpectedData.index)(我希望它会有所不同)替换所有内容。

您可以先创建一列 True 值,然后才替换 False 值:

myTempData['Actuals'] = True
myTempData.iloc[MyExpectedIndex] = False

关于python - 为什么我得到 : "Length of values does not match length of index" error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35599256/

相关文章:

python - numpy.array 与 img_to_array

python - Pandas 无法重置索引,因为名称存在

python - Pandas 的年化返回率

python - 等同于'execfile'的Python 3.3

python - 组合时间序列中的相似信号

python - Pandas Dataframe 集类别 - pandas.Categorical.set_categories 中的 `inplace` 参数已弃用

python - 在 python 中打印数字的唯一因子

python - Pandas - 重新采样/按日期时间索引进行分组并执行计算

Python pandas 按多列分组的行总和

python - 使用条件 groupby 计算分类列的百分比并在 Python 中计数