如何一一复制Python数据框? [英] How to duplicate Python dataframe one by one?

查看:317
本文介绍了如何一一复制Python数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pandas.DataFrame,如下:

df1 = 
    a    b
0   1    2
1   3    4

我想让这三次成为:

df2 =
    a    b
0   1    2
0   1    2
0   1    2
1   3    4
1   3    4
1   3    4

df2是通过循环创建的,但效率不高.

df2 is made from a loop, but it is not efficient.

如何使用更快的矩阵方式从df1中获取df2?

How can I get df2 from df1 using a matrix way which is faster?

推荐答案

构建一维索引器以切片values数组和index.您还必须注意索引,以取得所需的结果.

Build a one dimensional indexer to slice both the the values array and index. You must take care of the index as well to get your desired results.

  • np.arange上使用np.repeat获取索引器
  • 使用此索引器在值和索引上构造一个新的数据框
  • use np.repeat on an np.arange to get the indexer
  • construct a new dataframe using this indexer on both values and the index
r = np.arange(len(df)).repeat(3)
pd.DataFrame(df.values[r], df.index[r], df.columns)

   a  b
0  1  2
0  1  2
0  1  2
1  3  4
1  3  4
1  3  4

这篇关于如何一一复制Python数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆