我的代码编译速度有问题。我知道如何解决,但这个解决方案相当缓慢。因此,我想问你,你是否有办法让它更聪明/更快
我有原始df(大约100k行),我想将每一行乘以4x(复制该行),然后jsut更改一列-stats1(对于axample add 1)-stats1在原始df中始终为5
DF:
Stats 1 Stats 2 Stats 3 Stats 4 Stats 5
Row 1 5 5 8 7 3
Row 2 5 8 3 7 9
Row 3 5 5 1 2 6
Output:
Stats 1 Stats 2 Stats 3 Stats 4 Stats 5
Row 1 5 5 8 7 3
Row 1 6 5 8 7 3
Row 1 7 5 8 7 3
Row 1 8 5 8 7 3
Row 2 5 8 3 7 9
Row 2 6 8 3 7 9
Row 2 7 8 3 7 9
Row 2 8 8 3 7 9
Row 3 5 5 1 2 6
Row 3 6 5 1 2 6
Row 3 7 5 1 2 6
Row 3 8 5 1 2 6
这段代码可以工作,但速度非常慢
new_df = pd.DataFrame()
for i in range(len(df)):
new = pd.DataFrame()
new = new.append([df.loc[[i]]]*4,ignore_index=True)
step = 0
for j in range(0,4):
new.loc[:,"Stats1"].iloc[j] = 5+step
step += 1
new_df = pd.concat([new_df,new])
new_df.reset_index(inplace = True, drop = True)
谢谢
如果输出行顺序无关紧要,您可以尝试如下操作。必须删除列名中的空格,才能使其与
assign
中的关键字参数一起工作基本上,我们将相同的数据帧连接4次,但在每个增量中,我们将
Stats1
列增加增量。您必须比较原始数据集上的性能看看这个:
这段代码应该做得更快:
结果是:
希望这有帮助
相关问题 更多 >
编程相关推荐