李博洋*_*李博洋 4 python dataframe pandas
我有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从df1使用矩阵方式这是更快?
构建一维索引器来切割values数组和index.您还必须处理索引以获得所需的结果.
np.repeat上np.arange获得索引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
我不知道它是否比你的循环更有效,但它很容易构造为:
代码:
pd.concat([df] * 3).sort_index()
测试代码:
df = pd.DataFrame([[1, 2], [3, 4]], columns=list('ab'))
print(pd.concat([df] * 3).sort_index())
结果:
   a  b
0  1  2
0  1  2
0  1  2
1  3  4
1  3  4
1  3  4
| 归档时间: | 
 | 
| 查看次数: | 410 次 | 
| 最近记录: |