How to Fix: Length of values does not match length of index
In this article we will fix the error: The length of values does not match the length of the index in Python.
Cases of this error occurrence:
ValueError: Length of values (7) does not match length of index (10)
Reason for the error :
The length of the index of the pandas DataFrame(i.e length of the column of present DataFrame) which is 10 in this case is not equal to the length of the new list or NumPy array which is 7 in this case.
Fixing the error:
This error can be fixed by preprocessing the new list or NumPy array that is going to be a column of the DataFrame by using the pandas Series() function which actually converts the list or NumPy array into the size of the DataFrame column length by adding NaN if list or NumPy array has lesser length else if the list or NumPy has greater length then it takes the list or NumPy array with the length of columns of the pandas dataframe.
Syntax For list:
Consider list1 as a python list
df['new_column'] = pd.Series(list1)
Syntax For NumPy array:
Consider numarr as a numpy array
df['new_column'] = pd.Series(numarr)