ValueError: Columns must be same length as key ( Solved )

ValueError: Columns must be the same length as the key error occurs when we try to assign pandas dataframe to another dataframe where the number of rows is not the same.  In easier words, suppose you have one dataframe of shape (4,2) and another dataframe of (3,2) shape.  Now if you want to extend the first dataframe by adding another dataframe as the column, you will end up with this error. In this article, we will explore the exact scenario.

ValueError: Columns must be same length as key ( Replication ) –

Let us create two different pandas dataframe with different rows and index keys. Here is the complete code.

import pandas as pd
data1 = {
    'Col1' : ['A', 'B', 'C', 'D'],
    'Col2' : [23, 21, 22, 21],
}
df1 = pd.DataFrame(data)

data2 = {
    'Col1' : ['A', 'B', 'C']
        }
df2 = pd.DataFrame(data2)
dummy dataframe with different rows
dummy dataframe with different rows

Now let’s try to extend the column of the first dataframe. Since the second dataframe has only one column. then we create a single column in the first dataframe and then try to assign the second dataframe to the first column. Here is the code but it will throw the Columns that must be the same length as the key error.

df1[['col3']]=df2['Col1']
ValueError Columns must be same length as key
ValueError Columns must be same length as key

 

ValueError: Columns must be same length as key ( Solution ) –

We can fix up this error with two approaches. Let’s explore them one by one.

Solution 1: Using Merge in the place of assignment –

Since merge only maintain those rows which have the common key. We can use left join here which will keep the first dataframe completely and intersecting rows of dataframe 2. Here is the code for merging.

df1=df1.merge(df2)

Solution 2: Increasing row and make dataframe rows equivalent –

If the number of rows in both the dataframe are not equivalent then we can add extra rows with None data and then assign the new column as dataframe it will fix up the error. We can delete as well but this will be information loss.

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages Datasciencelearner.com, where he and his team share knowledge and help others learn more about data science.
Share via
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner