How to change date in pandas dataframe
<p>I have dataframe like below</p>

<pre><code>     day
0  2016-07-12
1  2016-08-13
2  2016-09-14
3  2016-10-15
4  2016-11-01

dtype:datetime64
</code></pre>

<p>I would like to change the day like below</p>

<pre><code>     day
0  2016-07-01
1  2016-08-01
2  2016-09-01
3  2016-10-01
4  2016-11-01
</code></pre>

<p>I tried</p>

<pre><code>df.day.dt.day=1
</code></pre>

<p>but It didnt work well
How can I transform?</p>

<p>You can use <code>numpy</code>, first convert to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a> and then convert to <code>datetime64[M]</code> by <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html" rel="nofollow"><code>astype</code></a>, what is the fastest solution:</p>

<pre><code>df['day'] = df['day'].values.astype('datetime64[M]')
print (df)
         day
0 2016-07-01
1 2016-08-01
2 2016-09-01
3 2016-10-01
4 2016-11-01
</code></pre>

<hr>

<p>Another slowier solution:</p>

<pre><code>df['day'] = df['day'].map(lambda x: pd.datetime(x.year, x.month, 1))
print (df)
         day
0 2016-07-01
1 2016-08-01
2 2016-09-01
3 2016-10-01
4 2016-11-01
</code></pre>

<p><strong>Timings</strong>:</p>

<pre><code>#[50000 rows x 1 columns]
df = pd.concat([df]*10000).reset_index(drop=True)

def f(df):
    df['day'] = df['day'].values.astype('datetime64[M]')
    return df

print (f(df))    

In [281]: %timeit (df['day'].map(lambda x: pd.datetime(x.year, x.month, 1)))
10 loops, best of 3: 160 ms per loop

In [282]: %timeit (f(df))
100 loops, best of 3: 4.38 ms per loop
</code></pre>

python pandas