gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:31:17 25 4
gpt4 key购买 nike

有没有更快的方法来获取此代码?我只想计算 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

最佳答案

您可以减去GesamteMessung_Sec列的最后一个值并添加to_frameSeries 转换为 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

关于python - 创建新列而不是 for 循环的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52836112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com