0

Tengo un dataframe con esta estructura:

    Item(s) Item 1  Item 2  Item 3  Item 4  Item 5  Item 6  Item 7  Item 8  Item 9  ... Item 23 Item 24 Item 25 Item 26 Item 27 Item 28 Item 29 Item 30 Item 31 Item 32
0   4   citrus fruit    semi-finished bread margarine   ready soups NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1   3   tropical fruit  yogurt  coffee  NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2   1   whole milk  NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3   4   pip fruit   yogurt  cream cheese    meat spreads    NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

Por otro lado tengo una lista con los valores de cada producto:

{1: nan, 2: 'decalcifier', 3: 'male cosmetics', 4: 'cake bar', 5: 'pudding powder', 6: 'curd', 7: 'frozen potato products', 8: 'other vegetables', 9: 'soap', 10: 'rice', 11: 'frankfurter', 12: 'liquor (appetizer)', 13: 'frozen fish', 14: 'cleaner', 15: 'candy', 16: 'coffee', 17: 'butter', 18: 'beef', 19: 'specialty chocolate', 20: 'Instant food products', 21: 'waffles', 22: 'spread cheese', 23: 'bathroom cleaner', 24: 'domestic eggs', 25: 'curd cheese', 26: 'pastry', 27: 'honey', 28: 'whole milk',

Cómo podría sustituir en el dataframe cada variable por su valor?? Es decir, q en todas las NaN pusieran un 1, decalcifier un 2...

3
  • Buen día, el diccionario lo tienes ya fijo? O es posible invertirlo? el 12 may. 2022 a las 11:51
  • Me valdría tanto fijo o pudiendo modificarlo siempre y cuando se mantengan los mismos valores en las distintas columnas. Es decir, que NaN siempre fuese 0, por ejemplo.
    – Rafael
    el 12 may. 2022 a las 13:59
  • Buen día, si la respuesta te fue útil no olvides aceptarla, de esa forma ayudas a otros usuarios a encontrar la solución a preguntas similares y al mismo tiempo ayudas a la comunidad a mantener abiertas únicamente las preguntas que no han sido resueltas. ¿Qué debo hacer cuando alguien contesta mi pregunta? el 24 jun. 2022 a las 2:18

1 respuesta 1

0

Buen día,

Una forma muy fácil de hacerlo es utilizando el método pandas.DataFrame.replace, pero la estructura del diccionario sería invirtiendo tus llaves y tus valores. Es decir, en lugar de 1: nan debería ser nan: 1

Por cierto, para poder sustituir los valores NaN debes utilizar numpy.nan

Utilizando una versión reducida (Solo 9 columnas) de las filas que pusiste en tu pregunta (Cree un archivo llamado sample.csv)

    Item(s) Item 1  Item 2  Item 3  Item 4  Item 5  Item 6  Item 7  Item 8  Item 9
0   4   citrus fruit    semi-finished   bread margarine ready soups NaN NaN NaN NaN NaN
1   3   tropical fruit  yogurt  coffee  NaN NaN NaN NaN NaN NaN
2   1   whole milk  NaN NaN NaN NaN NaN NaN NaN NaN
3   4   pip fruit   yogurt  cream cheese    meat spreads    NaN NaN NaN NaN NaN

E invirtiendo el diccionario (Por cierto en tu pregunta sólo pusiste hasta 28 así que los demás valores no supe que ponerles)

d = {np.nan:1, 'decalcifier': 2, 'male cosmetics': 3, 'cake bar': 4,
     'pudding powder': 5, 'curd': 6, 'frozen potato products': 7, 'other vegetables':8,
     'soap': 9, 'rice':10, 'frankfurter':11, 'liquor (appetizer)': 12,
     'frozen fish': 13, 'cleaner': 14, 'candy': 15, 'coffee': 16,
     'butter': 17, 'beef': 18, 'specialty chocolate': 19, 'Instant food products': 20,
     'waffles': 21, 'spread cheese': 22, 'bathroom cleaner': 23, 'domestic eggs': 24,
     'curd cheese': 25, 'pastry': 26, 'honey': 27, 'whole milk':28}

Lo único que hay que hacer para que reemplace todo lo que venga en el Diccionario por sus valores es:

df.replace(d)

Ejemplo complete:

import pandas as pd
import numpy as np

d = {np.nan:1, 'decalcifier': 2, 'male cosmetics': 3, 'cake bar': 4,
     'pudding powder': 5, 'curd': 6, 'frozen potato products': 7, 'other vegetables':8,
     'soap': 9, 'rice':10, 'frankfurter':11, 'liquor (appetizer)': 12,
     'frozen fish': 13, 'cleaner': 14, 'candy': 15, 'coffee': 16,
     'butter': 17, 'beef': 18, 'specialty chocolate': 19, 'Instant food products': 20,
     'waffles': 21, 'spread cheese': 22, 'bathroom cleaner': 23, 'domestic eggs': 24,
     'curd cheese': 25, 'pastry': 26, 'honey': 27, 'whole milk':28}

df = pd.read_csv('sample.csv')
df = df.replace(d)

Al imprimir df devuelve:

    Item(s) Item 1  Item 2  Item 3  Item 4  Item 5  Item 6  Item 7  Item 8  Item 9
0   4   citrus fruit    semi-finished   bread margarine ready soups 1.0 1.0 1.0 1.0 1.0
1   3   tropical fruit  yogurt  16  1   1.0 1.0 1.0 1.0 1.0
2   1   28  1   1   1   1.0 1.0 1.0 1.0 1.0
3   4   pip fruit   yogurt  cream cheese    meat spreads    1.0 1.0 1.0 1.0 1.0

Como mencioné, los valores que no se sustituyeron es porque no existen en el diccionario por lo que tendrás que agregar los elementos faltantes.

Nota: Si no quieres que aparezcan como float puedes cambiar el tipo de dato a entero.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.