Search code examples
pythonpandas

add columns different length pandas


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?


Solution

  • Use concat and pass axis=1 and ignore_index=True:

    In [38]:
    
    import numpy as np
    df = pd.DataFrame({'a':np.arange(5)})
    df1 = pd.DataFrame({'b':np.arange(4)})
    print(df1)
    df
       b
    0  0
    1  1
    2  2
    3  3
    Out[38]:
       a
    0  0
    1  1
    2  2
    3  3
    4  4
    In [39]:
    
    pd.concat([df,df1], ignore_index=True, axis=1)
    Out[39]:
       0   1
    0  0   0
    1  1   1
    2  2   2
    3  3   3
    4  4 NaN