【发布时间】:2019-06-07 17:45:20
【问题描述】:
我的数据看起来像这样(我已将 'rule_id' 设置为索引):
rule_id a b c d
50378 2 0 0 5
50402 12 9 6 0
52879 0 4 3 2
使用此代码后:
coeff = df.T
# compute the coefficients
for name, s in coeff.items():
top = 100 # start at 100
r = []
for i, v in enumerate(s):
if v == 0: # reset to 100 on a 0 value
top=100
else:
top = top/2 # else half the previous value
r.append(top)
coeff.loc[:, name] = r # set the whole column in one operation
# transpose back to have a companion dataframe for df
coeff = coeff.T
# build a new column from 2 consecutive ones, using the coeff dataframe
def build_comp(col1, col2, i):
conditions = [(df[col1] == 0) & (df[col2] == 0), (df[col1] != 0) & (df[col2] == 0), (df[col1] == df[col2]),
(df[col1] != 0) & (df[col2] != 0)]
choices = [np.nan , 100 , coeff[col1] , df[col2]/df[col1]*coeff[col1]+coeff[col1]]
df['comp{}'.format(i)] = np.select(conditions , choices)
old = df.columns[0] # store name of first column
#Ok, enumerate all the columns (except first one)
for i, col in enumerate(df.columns[1:], 1):
build_comp(old, col, i)
old = col # keep current column name for next iteration
# special processing for last comp column
df['comp{}'.format(i+1)] = np.where(df[col] == 0, np.nan, 100)
我的数据如下所示:
rule_id a b c d comp1 comp2 comp3 comp4
50378 2 0 0 5 100 NaN NaN 100
50402 12 9 6 0 87.5 41.66 100 NaN
52879 0 4 3 2 NaN 87.5 41.66 100
所以这里的“df”是存储我上面提到的数据的数据框。 看第一行。根据我的代码,如果比较两列并且第一列具有非零值(2)并且第二列具有 0 ,那么 100 应该在新列中更新,我能够实现,如果有多个非零值之间的比较(看第2行),那么比较是这样的:
9/12 *50 +50 = 87.5
然后
6/9 * 25 + 25 = 41.66
我能够实现,但列 'c' 和值 6 和 0 之间的 'd' 之间的第三个比较应该是:
0/6 *12.5 + 12.5 = 12.5
我在实现时遇到了问题。因此,第 2 行 comp3 中的值应该是 12.5,而不是 100。最后一行也是如此,其中值为 4 ,3 和 2
这是我想要的结果:
rule_id a b c d comp1 comp2 comp3 comp4
50378 2 0 0 5 100 NaN NaN 100
50402 12 9 6 0 87.5 41.66 12.5 NaN
52879 0 4 3 2 NaN 87.5 41.66 12.5
【问题讨论】:
-
您好,这很难理解...您能否尝试创建一个无法按预期工作的最小示例?
-
好的,当然。我将编辑我的问题
-
嗨@Joël,我已经编辑了我的问题,请看一下
-
谢谢,更清楚了;你能再次发布预期的内容吗?
-
我已根据您@Joël 的评论更新了我的问题。