add column with constant value to pandas dataframe

I don't know why this puts NaN into 'new' column?

    df['new'] = pd.Series([0 for x in range(len(df.index))])

EDIT:

    df['new'] = 0

works :)

The reason this puts NaN into a column is because df.index and the Index of your right-hand-side object are different. @zach shows the proper way to assign a new column of zeros. In general, pandas tries to do as much alignment of indices as possible. One downside is that when indices are not aligned you get NaN wherever they aren't aligned. Play around with the reindex and align methods to gain some intuition for alignment works with objects that have partially, totally, and not-aligned-all aligned indices. For example here's how DataFrame.align() works with partially aligned indices:

    In [7]: from pandas import DataFrame

    In [8]: from numpy.random import randint

    In [9]: df = DataFrame({'a': randint(3, size=10)})

    In [10]:

    In [10]: df
    Out[10]:
       a
    0  0
    1  2
    2  0
    3  1
    4  0
    5  0
    6  0
    7  0
    8  0
    9  0

    In [11]: s = df.a[:5]

    In [12]: dfa, sa = df.align(s, axis=0)

    In [13]: dfa
    Out[13]:
       a
    0  0
    1  2
    2  0
    3  1
    4  0
    5  0
    6  0
    7  0
    8  0
    9  0

    In [14]: sa
    Out[14]:
    0     0
    1     2
    2     0
    3     1
    4     0
    5   NaN
    6   NaN
    7   NaN
    8   NaN
    9   NaN
    Name: a, dtype: float64

From: stackoverflow.com/q/24039023