close

[Solved] Pandas error in Python: columns must be same length as key

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Pandas error in Python: columns must be same length as key in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Pandas error in Python: columns must be same length as key Error Occurs?

Today I get the following error Pandas error in Python: columns must be same length as key in python.

How To Solve Pandas error in Python: columns must be same length as key Error ?

  1. How To Solve Pandas error in Python: columns must be same length as key Error ?

    To Solve Pandas error in Python: columns must be same length as key Error You need a bit modify solution, because sometimes it return 2 and sometimes only one column:

  2. Pandas error in Python: columns must be same length as key

    To Solve Pandas error in Python: columns must be same length as key Error You need a bit modify solution, because sometimes it return 2 and sometimes only one column:

Solution 1


You need a bit modify solution, because sometimes it return 2 and sometimes only one column:

df2 = pd.DataFrame({'STATUS':['Estimated 3:17 PM','Delayed 3:00 PM']})


df3 = df2['STATUS'].str.split(n=1, expand=True)
df3.columns = ['STATUS_ID{}'.format(x+1) for x in df3.columns]
print (df3)
  STATUS_ID1 STATUS_ID2
0  Estimated    3:17 PM
1    Delayed    3:00 PM

df2 = df2.join(df3)
print (df2)
              STATUS STATUS_ID1 STATUS_ID2
0  Estimated 3:17 PM  Estimated    3:17 PM
1    Delayed 3:00 PM    Delayed    3:00 PM

Another possible data – all data have no whitespaces and solution working too:

df2 = pd.DataFrame({'STATUS':['Canceled','Canceled']})

and solution return:

print (df2)
     STATUS STATUS_ID1
0  Canceled   Canceled
1  Canceled   Canceled

All together:

df3 = df2['STATUS'].str.split(n=1, expand=True)
df3.columns = ['STATUS_ID{}'.format(x+1) for x in df3.columns]
df2 = df2.join(df3)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read