Python – add columns different length pandas

pandaspython

I have a problem with adding columns in pandas.
I have DataFrame, dimensional is nxk. And in process I wiil need add columns with dimensional mx1, where m = [1,n], but I don't know m.

When I try do it:

df['Name column'] = data    
# type(data) = list

result:

AssertionError: Length of values does not match length of index   

Can I add columns with different length?

Best Answer

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.