add columns different length pandas

If you use accepted answer, you’ll lose your column names, as shown in the accepted answer example, and described in the documentation (emphasis added):

The resulting axis will be labeled 0, …, n – 1. This is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information.

It looks like column names ('Name column') are meaningful to the Original Poster / Original Question.

To save column names, use pandas.concat, but don’t ignore_index (default value of ignore_index is false; so you can omit that argument altogether). Continue to use axis=1:

import pandas

# Note these columns have 3 rows of values:
original = pandas.DataFrame({
    'Age':[10, 12, 13], 
    'Gender':['M','F','F']
})

# Note this column has 4 rows of values:
additional = pandas.DataFrame({
    'Name': ['Nate A', 'Jessie A', 'Daniel H', 'John D']
})

new = pandas.concat([original, additional], axis=1) 
# Identical:
# new = pandas.concat([original, additional], ignore_index=False, axis=1) 

print(new.head())

#          Age        Gender        Name
#0          10             M      Nate A
#1          12             F    Jessie A
#2          13             F    Daniel H
#3         NaN           NaN      John D

Notice how John D does not have an Age or a Gender.

Leave a Comment