使用for循环和append创建新df的更快方法

2024-10-05 15:18:51 发布

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

我的代码编译速度有问题。我知道如何解决,但这个解决方案相当缓慢。因此,我想问你,你是否有办法让它更聪明/更快

我有原始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)

谢谢


Tags: 代码intruedataframedfnewforstats
2条回答

如果输出行顺序无关紧要,您可以尝试如下操作。必须删除列名中的空格,才能使其与assign中的关键字参数一起工作

df.columns = [name.replace(' ', '') for name in df.columns]
new_df = pd.concat([df.assign(Stats1=lambda x: x.Stats1 + i) for i in range(4)])

基本上,我们将相同的数据帧连接4次,但在每个增量中,我们将Stats1列增加增量。您必须比较原始数据集上的性能

看看这个:

df = pd.DataFrame(data={'Stats 1': [5, 5, 5],
                        'Stats 2': [5, 8, 5],
                        'Stats 3': [8, 3, 1],
                        'Stats 4': [7, 7, 2],
                        'Stats 5': [3, 9, 6]},
                  index=pd.Index(data=['Row 1', 'Row 2', 'Row 3']))

这段代码应该做得更快:

df_new = pd.concat([df] * 4).sort_index()

generator = (i for i in range(0, 4))
col = pd.Series(generator)

df_new.reset_index(inplace=True, drop=True)
df_new['Stats 1'] = df_new['Stats 1'] + pd.concat([col] * int(len(df_new) / 4)).reset_index(drop=True)

结果是:

      Stats 1  Stats 2  Stats 3  Stats 4  Stats 5
    0       5        5        8        7        3
    1       6        5        8        7        3
    2       7        5        8        7        3
    3       8        5        8        7        3
    4       5        8        3        7        9
    5       6        8        3        7        9
    6       7        8        3        7        9
    7       8        8        3        7        9
    8       5        5        1        2        6
    9       6        5        1        2        6
    10      7        5        1        2        6
    11      8        5        1        2        6

希望这有帮助

相关问题 更多 >