创建新列而不是for循环的更好方法

2024-10-03 17:19:21 发布

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

有没有更快的方法来处理这个代码? 我只想计算t\u last-t\u 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


Tags: 方法代码dataframedfforindextimesec
1条回答
网友
1楼 · 发布于 2024-10-03 17:19:21

您可以用列GesamteMessung_Sec减去最后一个值,然后加上^{},将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

如果需要原始数据帧的新列:

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

相关问题 更多 >