Using set_index within a custom function
<p>I would like to convert the date observations from a column into the index for my dataframe. I am able to do this with the code below:</p>

<p>Sample data:</p>

<pre><code>test = pd.DataFrame({'Values':[1,2,3], 'Date':["1/1/2016 17:49","1/2/2016 7:10","1/3/2016 15:19"]})
</code></pre>

<p>Indexing code:</p>

<pre><code>test['Date Index'] = pd.to_datetime(test['Date'])
test = test.set_index('Date Index')
test['Index'] = test.index.date
</code></pre>

<p>However when I try to include this code in a function, I am able to create the 'Date Index' column but <code>set_index</code> does not seem to work as expected.</p>

<pre><code>def  date_index(df):
     df['Date Index'] = pd.to_datetime(df['Date'])
     df = df.set_index('Date Index')
     df['Index'] = df.index.date
</code></pre>

<p>If I inspect the output of not using a function <code>info()</code> returns:</p>

<pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt;
DatetimeIndex: 3 entries, 2016-01-01 17:49:00 to 2016-01-03 15:19:00
Data columns (total 3 columns):
Date      3 non-null object
Values    3 non-null int64
Index     3 non-null object
dtypes: int64(1), object(2)
memory usage: 96.0+ bytes
</code></pre>

<p>If I inspect the output of the function <code>info()</code> returns:</p>

<pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt;
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
Date      3 non-null object
Values    3 non-null int64
dtypes: int64(1), object(1)
memory usage: 120.0+ bytes
</code></pre>

<p>I would like the <code>DatetimeIndex</code>.</p>

<p>How can <code>set_index</code> be used within a function? Am I using it incorrectly? </p>

<p>IIUC <code>return df</code> is missing:</p>

<pre><code>df1 = pd.DataFrame({'Values':[1,2,3], 'Exam Completed Date':["1/1/2016 17:49","1/2/2016 7:10","1/3/2016 15:19"]})

def  date_index(df):
     df['Exam Completed Date Index'] = pd.to_datetime(df['Exam Completed Date'])
     df = df.set_index('Exam Completed Date Index')
     df['Index'] = df.index.date
     return df

print (date_index(df1))
                          Exam Completed Date  Values       Index
Exam Completed Date Index                                        
2016-01-01 17:49:00            1/1/2016 17:49       1  2016-01-01
2016-01-02 07:10:00             1/2/2016 7:10       2  2016-01-02
2016-01-03 15:19:00            1/3/2016 15:19       3  2016-01-03
</code></pre>

<hr>

<pre><code>print (date_index(df1).info())
&lt;class 'pandas.core.frame.DataFrame'&gt;
DatetimeIndex: 3 entries, 2016-01-01 17:49:00 to 2016-01-03 15:19:00
Data columns (total 3 columns):
Exam Completed Date    3 non-null object
Values                 3 non-null int64
Index                  3 non-null object
dtypes: int64(1), object(2)
memory usage: 96.0+ bytes
None
</code></pre>

python pandas