python - How to return the Index when slicing Pandas Dataframe -


 df2=   pd.dataframe(df1.iloc[:, [n n in random.sample(range(1, 7), 3)]]) 

returns df1 rows , selected columns returns generic index 0,1,2,3..etc instead of returning datetime index of df1 want keep. tried:

df2=df1.copy(deep=true)  df2= pd.dataframe(data=none, columns=df1.columns, index=df1.index) df2= df1.iloc[:, [n n in random.sample(range(1, 7), 3)]] 

but not work...

try this:

df2 = pd.dataframe(df1.ix[:,random.sample(range(1,7),3)]) 

this give result wanted.

df1 out[130]:     1  2 d  nan  4.0 b  2.0  2.0 c  3.0  3.0  1.0  1.0  df1.ix[:,random.sample(range(0,2),2)] out[131]:     2  1 d  4.0  nan b  2.0  2.0 c  3.0  3.0  1.0  1.0 

this randomly sample columns , returns them in df2. return rows of randomly sampled columns index in df1.

edit- maxu has suggested, can use:

df2 = df1.ix[:, random.sample(df.columns.tolist(), 3)].copy() 

instead of calling pd.dataframe() constructor.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -