How to return the Index when slicing Pandas Dataframe
<pre><code> df2=   pd.DataFrame(df1.iloc[:, [n for n in random.sample(range(1, 7), 3)]])
</code></pre>

<blockquote>
  <p>returns df1 rows and selected columns but it returns a generic index 0,1,2,3..etc instead
  of   returning       the Datetime index of df1 which is what I want to keep. I tried:</p>
</blockquote>

<pre><code>df2=df1.copy(deep=True)

df2= pd.DataFrame(data=None, columns=df1.columns, index=df1.index)
df2= df1.iloc[:, [n for n in random.sample(range(1, 7), 3)]]
</code></pre>

<p>but it does not work... </p>

<p>Try this:</p>

<pre><code>df2 = pd.DataFrame(df1.ix[:,random.sample(range(1,7),3)])
</code></pre>

<p>This will give the result you wanted. </p>

<pre><code>df1
Out[130]: 
   one  two
d  NaN  4.0
b  2.0  2.0
c  3.0  3.0
a  1.0  1.0

df1.ix[:,random.sample(range(0,2),2)]
Out[131]: 
   two  one
d  4.0  NaN
b  2.0  2.0
c  3.0  3.0
a  1.0  1.0
</code></pre>

<p>This will randomly sample your columns and returns them in df2. This will return all the rows of the randomly sampled columns with index as was in df1.</p>

<p>Edit-
As MaxU has suggested, you can simply use:</p>

<pre><code>df2 = df1.ix[:, random.sample(df.columns.tolist(), 3)].copy()
</code></pre>

<p>instead of calling the pd.DataFrame() constructor.</p>

python pandas indexing dataframe slice