【问题标题】:better way to create a new column instead of for loop创建新列而不是 for 循环的更好方法
【发布时间】:2019-03-21 00:36:19
【问题描述】:

有没有更快的方法来处理这段代码? 我只想计算 t_last - t_i 并创建一个新列

time_ges = pd.DataFrame()
for i in range(0, len(df.GesamteMessung_Sec.index), 1):
    time = df.GesamteMessung_Sec.iloc[-1]-df.GesamteMessung_Sec.iloc[i]
    time_ges = time_ges.append(pd.DataFrame({'echte_Ladezeit': time}, index=[0]), ignore_index=True)

df['echte_Ladezeit'] = time_ges

这段代码需要大量的计算时间,有没有更好的方法来做到这一点? 谢谢,R

【问题讨论】:

    标签: python pandas performance for-loop


    【解决方案1】:

    您可以通过GesamteMessung_Sec 列减去最后一个值并添加to_frame 以将Series 转换为DataFrame

    df = pd.DataFrame({'GesamteMessung_Sec':[10,2,1,5]})
    print (df)
       GesamteMessung_Sec
    0                  10
    1                   2
    2                   1
    3                   5
    
    time_ges = (df.GesamteMessung_Sec.iloc[-1] - df.GesamteMessung_Sec).to_frame('echte_Ladezeit')
    print (time_ges )
       echte_Ladezeit
    0              -5
    1               3
    2               4
    3               0
    

    如果需要原始DataFrame的新列:

    df = pd.DataFrame({'GesamteMessung_Sec':[10,2,1,5]})
    df['echte_Ladezeit'] = df.GesamteMessung_Sec.iloc[-1] - df.GesamteMessung_Sec
    print (df)
       GesamteMessung_Sec  echte_Ladezeit
    0                  10              -5
    1                   2               3
    2                   1               4
    3                   5               0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      相关资源
      最近更新 更多