Mirando los datos veo que las listas son simplemente strings. Para distinguir un string corriente de una lista mostrada como string, miramos el primer y último caracter, que tienen que ser "[" y "]"
Esta función evalúa si un valor es una lista o no. La comprobación se limita a revisar que empiece y termine con "[" y "]". Si es necesario, se puede hacer más estricta, chequeando que contenga valores separados por coma.
import pandas as pd
def is_a_lista(valor):
""" Evalua si el valor es una lista representada como string
@param valor: El valor a probar.
@return: True si es una lista.
"""
return type(valor) is str and valor[0] == "[" and valor[-1] == "]"
Esta función recorre una fila. Cuando encuentra una celda con listas, corre todo el contenido de la fila una celda a la izquierda y agrega una celda en blanco al final (se puede ajustar)
def ajusta_fila(row):
""" Ajusta una fila del dataframe, eliminando las celdas con listas
@param row: Una fila
@return: La fila, compactada y sin listas.
@return: Un arreglo de indices (de row) donde se encontraron listas
"""
salida = []
indices = []
for index in range(len(row)):
valor = row[index]
if is_a_lista(valor):
indices.append(index)
else:
salida.append(valor)
salida.extend([''] * (len(row) - len(salida)))
return salida, indices
La fila original no se toca; la función retorna la nueva fila y un arreglo con los indices (de la fila original) en donde se encontraron listas. Esto lo uso luego para chequear los resultados.
Con esto estamos listos.
Comprobación
Ahora haremos un programa de comprobación.
Revisaremos cada fila de la siguiente manera: si se detectan listas, se imprime el valor de la celda original. Debajo mostramos las celdas anteriores/posteriores en la fila original. A continuación mostramos la parte correspondiente en la nueva fila, para revisar visualmente que el cambio esté bien hecho.
df = pd.read_csv("/home/candid/PycharmProjects/archivo.csv", dtype=str)
for index, row in df.iterrows():
if index > 10:
break
new_row, indices = ajusta_fila(row)
desp = 0
if len(indices):
print()
print("Fila %3d cambiada en columnas " % index)
for indice in indices:
print(" Celda %3d - Valor: %s" % (indice, row[indice]))
print(" Contenido original")
for i in range(indice-1, indice+3):
print(" row[%d]=%s" % (i, row[i]))
print(" --------------------")
print(" Contenido modificado")
for i in range(indice - desp - 1, indice - desp + 2):
print(" new_row[%d]=%s" % (i, new_row[i]))
desp += 1
print()
print()
Lo cual produce:
Fila 0 cambiada en columnas
Celda 3 - Valor: ['In next 3 months', 'In next 6 months', 'In next 1 year', 'Only once COVID-19 is under control', 'Only once COVID-19 vaccine is developed']
Contenido original
row[2]=When do you think your next vacation can start?
row[3]=['In next 3 months', 'In next 6 months', 'In next 1 year', 'Only once COVID-19 is under control', 'Only once COVID-19 vaccine is developed']
row[4]=nan
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=When do you think your next vacation can start?
new_row[3]=nan
new_row[4]=Multiple Choice
Celda 7 - Valor: ['think', 'vacat', 'start']
Contenido original
row[6]=Hotel ABC
row[7]=['think', 'vacat', 'start']
row[8]=In next 3 months
row[9]=In next 6 months
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=In next 3 months
new_row[7]=In next 6 months
Fila 1 cambiada en columnas
Celda 3 - Valor: ["Doctor's availability in hotel", 'Ventilator availability in hotel', 'Tie-ups with nearby hospitals', 'Availability of medical rooms with primary first aid care']
Contenido original
row[2]=What are your preferences regarding medical treatment policy (with additional cost)?
row[3]=["Doctor's availability in hotel", 'Ventilator availability in hotel', 'Tie-ups with nearby hospitals', 'Availability of medical rooms with primary first aid care']
row[4]=nan
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=What are your preferences regarding medical treatment policy (with additional cost)?
new_row[3]=nan
new_row[4]=Multiple Choice
Celda 7 - Valor: ['prefer', 'medic', 'treatment', 'polici', 'addit', 'cost']
Contenido original
row[6]=Hotel ABC
row[7]=['prefer', 'medic', 'treatment', 'polici', 'addit', 'cost']
row[8]=Doctor's availability in hotel
row[9]=Ventilator availability in hotel
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Doctor's availability in hotel
new_row[7]=Ventilator availability in hotel
Fila 2 cambiada en columnas
Celda 3 - Valor: ['Buffet breakfast with social distancing', 'Buffet breakfast replaced with Ala-carte with limited options', 'Breakfast to be delivered in room with limited options (chargeable)', 'Packaged breakfast only']
Contenido original
row[2]=What is your preferences of complementary breakfast?
row[3]=['Buffet breakfast with social distancing', 'Buffet breakfast replaced with Ala-carte with limited options', 'Breakfast to be delivered in room with limited options (chargeable)', 'Packaged breakfast only']
row[4]=nan
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=What is your preferences of complementary breakfast?
new_row[3]=nan
new_row[4]=Multiple Choice
Celda 7 - Valor: ['prefer', 'complementari', 'breakfast']
Contenido original
row[6]=Hotel ABC
row[7]=['prefer', 'complementari', 'breakfast']
row[8]=Buffet breakfast with social distancing
row[9]=Buffet breakfast replaced with Ala-carte with limited options
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Buffet breakfast with social distancing
new_row[7]=Buffet breakfast replaced with Ala-carte with limited options
Fila 3 cambiada en columnas
Celda 3 - Valor: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Contenido original
row[2]=What is your preference for a in-hotel grocery shops for the basic necessity items and packaged food?
row[3]=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
row[4]=nan
row[5]=Likert Scale
--------------------
Contenido modificado
new_row[2]=What is your preference for a in-hotel grocery shops for the basic necessity items and packaged food?
new_row[3]=nan
new_row[4]=Likert Scale
Celda 7 - Valor: ['prefer', 'hotel', 'groceri', 'shop', 'basic', 'necess', 'item', 'packag', 'food']
Contenido original
row[6]=Hotel ABC
row[7]=['prefer', 'hotel', 'groceri', 'shop', 'basic', 'necess', 'item', 'packag', 'food']
row[8]=Not preferred
row[9]=2
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Not preferred
new_row[7]=2
Fila 4 cambiada en columnas
Celda 3 - Valor: ['Collect keys at the counter maintaining social distancing', 'Collect keys at the KIOSK using booking bar-code', 'Online Keys using the mobile App']
Contenido original
row[2]=What is your preference of hotel check-in?
row[3]=['Collect keys at the counter maintaining social distancing', 'Collect keys at the KIOSK using booking bar-code', 'Online Keys using the mobile App']
row[4]=Consumer Personality
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=What is your preference of hotel check-in?
new_row[3]=Consumer Personality
new_row[4]=Multiple Choice
Celda 7 - Valor: ['prefer', 'hotel', 'check']
Contenido original
row[6]=Hotel ABC
row[7]=['prefer', 'hotel', 'check']
row[8]=Collect keys at the counter maintaining social distancing
row[9]=Collect keys at the KIOSK using booking bar-code
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Collect keys at the counter maintaining social distancing
new_row[7]=Collect keys at the KIOSK using booking bar-code
Fila 5 cambiada en columnas
Celda 3 - Valor: ['Pay at the counter maintaining social distancing', 'Pay at KIOSK', 'Online payment using the mobile App']
Contenido original
row[2]=What is your preference of payment during Check-out?
row[3]=['Pay at the counter maintaining social distancing', 'Pay at KIOSK', 'Online payment using the mobile App']
row[4]=Consumer Personality
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=What is your preference of payment during Check-out?
new_row[3]=Consumer Personality
new_row[4]=Multiple Choice
Celda 7 - Valor: ['prefer', 'payment', 'check']
Contenido original
row[6]=Hotel ABC
row[7]=['prefer', 'payment', 'check']
row[8]=Pay at the counter maintaining social distancing
row[9]=Pay at KIOSK
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Pay at the counter maintaining social distancing
new_row[7]=Pay at KIOSK
Fila 6 cambiada en columnas
Celda 3 - Valor: ['Travel date change is preferred at no cost', 'Cancellation at some minimal cost (based on hotel policy)', 'Cancellation with some amount refund and hotel coupons for next visit']
Contenido original
row[2]=What is your preference of hotel cancellation / travel date change policy?
row[3]=['Travel date change is preferred at no cost', 'Cancellation at some minimal cost (based on hotel policy)', 'Cancellation with some amount refund and hotel coupons for next visit']
row[4]=Consumer Personality
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=What is your preference of hotel cancellation / travel date change policy?
new_row[3]=Consumer Personality
new_row[4]=Multiple Choice
Celda 7 - Valor: ['prefer', 'hotel', 'cancel', 'travel', 'date', 'chang', 'polici']
Contenido original
row[6]=Hotel ABC
row[7]=['prefer', 'hotel', 'cancel', 'travel', 'date', 'chang', 'polici']
row[8]=Travel date change is preferred at no cost
row[9]=Cancellation at some minimal cost (based on hotel policy)
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Travel date change is preferred at no cost
new_row[7]=Cancellation at some minimal cost (based on hotel policy)
Fila 7 cambiada en columnas
Celda 3 - Valor: ['Guests are allowed in living room with precautions', 'Guest are allowed only in certain designated areas', 'No guests are allowed inside hotel']
Contenido original
row[2]=What is your preference of the guest policy?
row[3]=['Guests are allowed in living room with precautions', 'Guest are allowed only in certain designated areas', 'No guests are allowed inside hotel']
row[4]=Consumer Personality
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=What is your preference of the guest policy?
new_row[3]=Consumer Personality
new_row[4]=Multiple Choice
Celda 7 - Valor: ['prefer', 'guest', 'polici']
Contenido original
row[6]=Hotel ABC
row[7]=['prefer', 'guest', 'polici']
row[8]=Guests are allowed in living room with precautions
row[9]=Guest are allowed only in certain designated areas
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Guests are allowed in living room with precautions
new_row[7]=Guest are allowed only in certain designated areas
Fila 8 cambiada en columnas
Celda 3 - Valor: ['Regular concierge services', 'Online concierge service']
Contenido original
row[2]=What is your preference of the concierge service?
row[3]=['Regular concierge services', 'Online concierge service']
row[4]=Consumer Personality
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=What is your preference of the concierge service?
new_row[3]=Consumer Personality
new_row[4]=Multiple Choice
Celda 7 - Valor: ['prefer', 'concierg', 'servic']
Contenido original
row[6]=Hotel ABC
row[7]=['prefer', 'concierg', 'servic']
row[8]=Regular concierge services
row[9]=Online concierge service
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Regular concierge services
new_row[7]=Online concierge service
Fila 9 cambiada en columnas
Celda 3 - Valor: ['Hand sanitizer', 'Face mask', 'Face sheild', 'Hand gloves', 'Personal thermometers', 'Phone sanitizer', '', 1]
Contenido original
row[2]=What are the items you feel are essential in your room?
row[3]=['Hand sanitizer', 'Face mask', 'Face sheild', 'Hand gloves', 'Personal thermometers', 'Phone sanitizer', '', 1]
row[4]=Consumer Intentions
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=What are the items you feel are essential in your room?
new_row[3]=Consumer Intentions
new_row[4]=Multiple Choice
Celda 7 - Valor: ['item', 'feel', 'essenti', 'room']
Contenido original
row[6]=Hotel ABC
row[7]=['item', 'feel', 'essenti', 'room']
row[8]=Hand sanitizer
row[9]=Face mask
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Hand sanitizer
new_row[7]=Face mask
Fila 10 cambiada en columnas
Celda 3 - Valor: ['Other people can be present maintaining social distancing', 'Individual usage based on time sharing (Not all time slots will be available)', 'I will not prefer Spa/Sauna at all']
Contenido original
row[2]=What is your preference of using the Spa/Sauna room?
row[3]=['Other people can be present maintaining social distancing', 'Individual usage based on time sharing (Not all time slots will be available)', 'I will not prefer Spa/Sauna at all']
row[4]=Consumer Intentions
row[5]=Multiple Choice
--------------------
Contenido modificado
new_row[2]=What is your preference of using the Spa/Sauna room?
new_row[3]=Consumer Intentions
new_row[4]=Multiple Choice
Celda 7 - Valor: ['prefer', 'sauna', 'room']
Contenido original
row[6]=Hotel ABC
row[7]=['prefer', 'sauna', 'room']
row[8]=Other people can be present maintaining social distancing
row[9]=Individual usage based on time sharing (Not all time slots will be available)
--------------------
Contenido modificado
new_row[5]=Hotel ABC
new_row[6]=Other people can be present maintaining social distancing
new_row[7]=Individual usage based on time sharing (Not all time slots will be available)