[英]Using a loop to get a sum of computed values (using column math) for each dataframe entry in pandas
I have the following data frame:我有以下数据框:
For each entry of this data frame, I am looking to get the sum of log(df['s_i']/df['s_18'])*log(i/18) for i in h = [18, 56, 98, 123, 148].对于这个数据帧的每个条目,我希望得到 log(df['s_i']/df['s_18'])*log(i/18) for i in h = [18, 56, 98 , 123, 148]。
I tried the following:我尝试了以下方法:
a = []
h = [18, 56, 98, 123, 148]
for i in df.index:
for zi in h:
a.append(log(df.loc[i,'s_'+str(zi)]/df.loc[i,'s_18'])*log(zi/18))
b = sum(a)
However, it did not work.但是,它没有用。 Any idea how to solve this problem?知道如何解决这个问题吗? Any help would be greatly appreciated!任何帮助将不胜感激!
Here one thing to note use np.log<i> or math.log
where is <i> base what ever you want
if you don't have any custom implementation log
function.如果您没有任何自定义实现log
function,这里需要注意的一件事是使用np.log<i> or math.log
where is <i> base what ever you want
基础。
zr
should to change to 18
as per your statement formula zr
应该根据您的语句公式更改为18
log(df['s_i']/df['s_18'])*log(i/18)
Here i am using similar layout dataframe
, please check out this code:这里我使用类似的布局dataframe
,请查看此代码:
import numpy as np
import pandas as pd
h = [18, 56, 98, 123, 148]
df = pd.DataFrame(
data= np.arange(1, 51).reshape(10, 5),
columns= ['s_'+str(i) for i in h]
)
# here one point should be noted that `b += sum(a)` should be in outer `for-loop`
# otherwise as `a` grows at each iteration its `all items again added` so put
# `b += sum(a) in outer for-loop`
b = 0
for i in df.index:
a = []
for zi in h:
a.append(np.log(df.loc[i,'s_'+str(zi)]/df.loc[i,'s_18'])*np.log(zi/18))
b += sum(a)
print(b)
Method-2方法二
equation = "np.log(df.loc[i,'s_'+str(j)]/df.loc[i,'s_18'])*np.log(j/18)"
b = 0
for i in df.index:
b += sum(list(map(lambda j: eval(equation), h)))
print(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.