Length of values does not match length of index

The ValueError: Length of values does not match length of index raised because the previous columns you have added in the DataFrame are not the same length as the most recent one you have attempted to add in the DataFrame. So, you need make sure that the length of the array you are assign to a new column is equal to the length of the dataframe .
import pandas as pd import numpy as np df = pd.DataFrame({'X': [1,2,3,4]}) df['Y'] = [3,4]
Above code will raise the error Length of values does not match length of index because the DataFrame has four rows but the list only two elements.

Solution:


how to solve Length of values does not match length of index
The simple solution is that you first convert the list/array to a pandas Series , and then when you do assignment, missing index in the Series will be filled with NaN values .
import pandas as pd import numpy as np df = pd.DataFrame({'X': [1,2,3,4]}) df['Y'] = pd.Series([3,4]) df
X Y 0 1 3.0 1 2 4.0 2 3 NaN 3 4 NaN