Python 为什么我得到:“值的长度与索引的长度不匹配”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35599256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:39:17  来源:igfitidea点击:

Why do I get: "Length of values does not match length of index" error?

pythonpandas

提问by Alexander UpUp

I have the following code and I'm trying to assign Trueto a new Column where Actual Date equals the Date in Column 'D' (Date created) and Falseto any other.

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

I'm quite new to Python so I would like to understand what I have done wrong:

我对 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()

Error

错误

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

采纳答案by Matheus Portela

My best guess relies in this part:

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

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

It first says that myTempData['Actuals']is a column of size len(MyActualData.index)containing only Truevalues. Next, it replaces everything by another column of size len(MyExpectedData.index)(which I expect to be different) containing Falsevalues.

它首先说这myTempData['Actuals']是一个len(MyActualData.index)只包含True值的大小列。接下来,它将所有内容替换len(MyExpectedData.index)为包含False值的另一列大小(我预计会有所不同)。

You can first create a column of Truevalues and, only then, replace Falseones:

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

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