如何在切片Pandas Datafram时返回索引

2024-04-25 10:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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:

^{pr2}$

但它不起作用。。。在


Tags: andofsampleindataframeforindexrange
2条回答

试试这个:

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

这会得到你想要的结果。在

^{pr2}$

这将随机抽取列的样本并在df2中返回它们。这将返回具有索引的随机抽样列的所有行,如df1中所示。在

编辑- 正如MaxU所建议的,您可以简单地使用:

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

而不是打电话给pd数据帧()构造函数。在

稍微不同一点的方法呢?在

In [66]: df
Out[66]:
            c1  c2  c3
2016-01-01   4   0   3
2016-01-02   2   3   2
2016-01-03   1   2   3
2016-01-04   3   3   0
2016-01-05   1   0   4
2016-01-06   1   1   1
2016-01-07   2   3   3
2016-01-08   2   2   2
2016-01-09   4   0   0
2016-01-10   1   1   0
2016-01-11   1   3   0
2016-01-12   4   3   1
2016-01-13   0   0   3
2016-01-14   3   1   0
2016-01-15   4   3   1

In [67]: rnd = df.sample(n=6)

In [68]: rnd.index
Out[68]: DatetimeIndex(['2016-01-04', '2016-01-03', '2016-01-12', '2016-01-02', '2016-01-01', '2016-01-13'], dtype='datetime64[ns]', freq=None)

In [69]: rnd
Out[69]:
            c1  c2  c3
2016-01-04   3   3   0
2016-01-03   1   2   3
2016-01-12   4   3   1
2016-01-02   2   3   2
2016-01-01   4   0   3
2016-01-13   0   0   3

相关问题 更多 >