我有一个包含4列的数据框:
c1 c2 c3 GName
0.221445 0.300534 5.689 KDD
0.001000 0.969000 15.140 ACC
1.000000 0.094000 -0.245 QETF
称为一列的file
数据框:
GName
Abd
kkoew
KDD
pwqh
ACC
dsewf
我需要添加新的列调用label
,该列调用基于检查c1, c2 and c3
和GName
中的得分
因此,如果3个分数中的大多数都同意其条件(3个分数中的2个或全部3个)并且GName的值存在于数据帧file
中; label
= 1,否则label
= 0
The conditions of c1 should be > 0.95
c2 should be > 0.50
c3 should be > 15
输出将如下所示:
c1 c2 c3 GName label
0.221445 0.300534 5.689 KDD 0 (because 0 out of 3 and KDD in file)
0.001000 0.969000 15.140 ACC 1 (because 2 out of 3 and ACC in file)
1.000000 0.94060 -0.245 QETF 0 (because 2 out of 3 but QETF not in file)
我正在努力应对这些不同的条件,请帮忙吗?
答案 0 :(得分:1)
我要这样做的方式是这样:
import pandas as pd
df = pd.DataFrame({'c1':[0.221445, 0.001000, 1.000000],
'c2':[0.300534, 0.969000, 0.094000],
'c3':[5.689, 15.140, -0.245],
'GName':['KDD', 'ACC', 'QETF']})
file = pd.DataFrame({'GName':['KDD', 'ACC']})
conditions = (df['c1'] > 0.95).astype(int) + (df['c2'] > 0.5).astype(int) + (df['c3'] > 15).astype(int)
conditions = (conditions >= 2) & (df['GName'].isin(file['GName']))
df['label'] = 0
df.loc[conditions, 'label'] = 1
>>> df
c1 c2 c3 GName label
0 0.221445 0.300534 5.689 KDD 0
1 0.001000 0.969000 15.140 ACC 1
2 1.000000 0.094000 -0.245 QETF 0
如果您也可以在问题中包含用于生成数据框的代码,那就太好了。