Kshitij Yadav:
Tengo un conjunto de datos que tiene los siguientes valores:
LabelA PositiveA NegativeA LabelB PositiveB NegativeB LabelC PositiveC NegativeC Final_Label
1 .60 .40 0 .30 .70 1 .9 .1 1
0 .1 .9 0 .49 .51 0 .3 .7 0
0 .34 .66 1 .87 .13 1 .90 .1 1
Final_label sería de 1 si la mayoría de las etiquetas (LABELA, LabelB y LabelC) sería 1 y viceversa.
Quiero calcular una columna llamada "polaridad", que tiene la siguiente defination:
- Si Final_label = 1, la polaridad es la media de todos los "PositiveA / B / C" cuya etiqueta fue también 1
- Si Final_label = 0, la polaridad es la media de todos los "NegativeA / B / C" cuya etiqueta fue también 0
Por ejemplo, en el conjunto de datos anterior, Polaridad tendría el siguiente valor:
Polarity
.75 (adding and taking average of PositiveA and PositiveC)
.7033 (adding and taking average of NegativeA and Negativeb and NegativeC)
.885 (adding and taking average of PositiveB and PositiveC)
¿Cómo implementar esto en Python? Por aquí he mostrado 3 columnas, en mi conjunto de datos que tengo 7 columnas de la etiqueta.
Quang Hoang:
Aquí está mi enfoque con where
y mask
:
# filter the labels, positives, negatives:
labels = df.filter(regex='Label\w').eq(1).values
positives = df.filter(regex='Positive\w')
negatives = df.filter(regex='Negative\w')
# output
df['Polarity'] = np.where(df['Final_Label'],
positives.where(labels).mean(axis=1),
negatives.mask(labels).mean(axis=1)
)
print(df['Polarity'])
Salida:
0 0.750000
1 0.703333
2 0.885000
Name: Polarity, dtype: float64