gpt4 book ai didi

python - 如何以最佳(Pythonic)方式编写这段代码?

转载 作者:行者123 更新时间:2023-12-01 01:30:09 24 4
gpt4 key购买 nike

我在 R 中有以下代码,我需要使用 pandas 在 python 中以最佳方式编写它。我写了,但是运行起来需要很长时间。

1)有人可以确认这相当于Python中的R代码

2)如何以Python方式编写(最佳方式)

在 R 中

for (i in 1:dim(df1)[1])
df1$column1[i] <- sum(df2[i,4:33])

在 Python 中

for i in range(df1.shape[0]):
df1['column1'][i] = df2.iloc[i,3:34].sum()

最佳答案

有两种方法可以进行替换

df1['column1'] = df2.iloc[:, 3:34].sum(axis=1)

或者

df1.loc[:, 'column1'] = df2.iloc[:, 3:34].sum(axis=1)

关于python - 如何以最佳(Pythonic)方式编写这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52957582/

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