Python 如果数据帧中的大多数列相等,则设置值
从我昨天提出的另一个问题开始 从@anky_91解决方案开始,我正在做类似的事情。 如果所有列都相等,我希望有更灵活的设置,而不是放置Python 如果数据帧中的大多数列相等,则设置值,python,pandas,Python,Pandas,从我昨天提出的另一个问题开始 从@anky_91解决方案开始,我正在做类似的事情。 如果所有列都相等,我希望有更灵活的设置,而不是放置1或-1。 事实上,我想要1,如果(例如)70%的列是1,-1,条件相同,但相反,否则为0 这就是我写的: # Instead of using .all I use .sum to count the occurence of 1 and 0 for each row m1 = local_df.eq(1).sum(axis=1) m2 = local_df.e
1
或-1
。
事实上,我想要1
,如果(例如)70%的列是1
,-1
,条件相同,但相反,否则为0
这就是我写的:
# Instead of using .all I use .sum to count the occurence of 1 and 0 for each row
m1 = local_df.eq(1).sum(axis=1)
m2 = local_df.eq(0).sum(axis=1)
# Debug print, it work
print(m1)
print(m2)
但我不知道如何改变这部分:
local_df['enseamble'] = np.select([m1, m2], [1, -1], 0)
m = local_df.drop(local_df.columns.difference(['enseamble']), axis=1)
我用伪代码编写我想要的:
tot = m1 + m2
if m1 > m2
if(m1 * 100) / tot > 0.7 # simple percentage calculus
df['enseamble'] = 1
else if m2 > m1
if(m2 * 100) / tot > 0.7 # simple percentage calculus
df['enseamble'] = -1
else:
df['enseamble'] = 0
谢谢
编辑1
这是一个预期输出的示例:
NET_0 NET_1 NET_2 NET_3 NET_4 NET_5 NET_6
date
2009-08-02 0 1 1 1 0 1
2009-08-03 1 0 0 0 1 0
2009-08-04 1 1 1 0 0 0
date enseamble
2009-08-02 1 # because 1 is more than 70%
2009-08-03 -1 # because 0 is more than 70%
2009-08-04 0 # because 0 and 1 are 50-50
您可以通过以下条件获得指定的输出:
thr = 0.7
c1 = (df.eq(1).sum(1)/df.shape[1]).gt(thr)
c2 = (df.eq(0).sum(1)/df.shape[1]).gt(thr)
c2.astype(int).mul(-1).add(c1)
输出
或使用
np。选择:
pd.DataFrame(np.select([c1,c2], [1,-1], 0), index=df.index, columns=['result'])
result
2009-08-02 0
2009-08-03 0
2009-08-04 0
2009-08-05 0
2009-08-06 -1
2009-08-07 1
尝试使用(m1
、m2
和tot
与您拥有的相同):
在这些更改之后,EnSamble列的输出现在应该是什么?相同:1
如果该行中的70%是1
,-1
如果70%是0
,0
否则我理解,只是想直观地查看输出列以进行交叉验证。同时,如果@yatu的解决方案有帮助,您可以查看它。:)已经测试过,它似乎无法100%正常工作:)你现在可以检查一下我问题中的示例吗c2。astype(int).mul(-1)+c1
似乎只适用于-1
而不适用于1
使用你的示例对我来说效果很好。也可以使用np.select。用np选中update@AsoStrifeOk。选择它似乎有效。我尝试了其他测试,并让您知道:)啊,我刚刚意识到我正在使用另一个测试的dfquestion@yatu我想这很好,尽管我认为预期的输出已经改变,所以请op提供这一信息。:)如果正确,我不是舒尔,因为我总是获得-1
。另外,如果我把1作为阈值,我必须获得与旧问题相同的结果。而且它不起作用。。。我尝试其他测试,让你know@AsoStrife我只是试着复制你的伪代码,但我认为yatu的sol应该可以工作,如果这个不行的话
pd.DataFrame(np.select([c1,c2], [1,-1], 0), index=df.index, columns=['result'])
result
2009-08-02 0
2009-08-03 0
2009-08-04 0
2009-08-05 0
2009-08-06 -1
2009-08-07 1
cond1=(m1>m2)&((m1 * 100/tot).gt(0.7))
cond2=(m2>m1)&((m2 * 100/tot).gt(0.7))
df['enseamble'] =np.select([cond1,cond2],[1,-1],0)
m =df.drop(df.columns.difference(['enseamble']), axis=1)
print(m)
enseamble
date
2009-08-02 1
2009-08-03 -1
2009-08-04 0