根据不同列的不同条件添加列| 0

2024-06-01 03:41:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含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 c3GName中的分数

因此,如果3个分数中的大多数都同意他们的条件(3分中的2分或全部3分),并且GName的值存在于数据帧filelabel=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)

我正与这些不同的情况作斗争,有什么帮助吗


Tags: andof数据belabelfileaccc2
1条回答
网友
1楼 · 发布于 2024-06-01 03:41:40

我会这样做:

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

如果您也能在问题中包含生成数据帧的代码,那就太好了

相关问题 更多 >