0

Tengo una dataframe de la cual quiero convertir parte de la línea en varias líneas. De hecho, las líneas representan una pregunta en la columna Questions y respuestas a estas preguntas en las lineas Answer_i.

    QID    Questions    QType    Answer_1     Answer_2    Answer_3    Answer_4 ...               
1263    1177    The travel restrictions of COVID-19 have been lifted and you are looking to book a flight. To what extent are the following factors considerations in your choice of flight?    Likert Scale    Very important consideration    Important consideration Somewhat consider   Not an important consideration  Do not consider Discounted flights  Very important consideration    Important consideration Somewhat consider   Not an important consideration  Do not consider Baggage policy Very important consideration Important consideration Somewhat consider   Not an important consideration  Do not consider

Me gustaria obtener, para esta lineas, la siguiente dataframe:

    QID    Questions    QType    Answer_1     Answer_2    Answer_3    Answer_4 ...    
1263    1177    The travel restrictions of COVID-19 have been lifted and you are looking to book a flight. To what extent are the following factors considerations in your choice of flight?    Likert Scale 
  Very important consideration  Important consideration Somewhat consider   Not an important consideration  Do not consider 
1264    1177_1  Discounted flights  Likert Scale    Very important consideration    Important consideration Somewhat consider   Not an important consideration  Do not consider 
1265    1177_2  Baggage policy    Likert Scale  Very important consideration    Important consideration Somewhat consider   Not an important consideration  Do not consider

Hasta hoy intenté iterar sobre las respuestas:

for i, row in df.iterrows():
    passed_items = []
    questions = row['Questions']
    for cell in row:
        if cell in passed_items:
            answers = {f"Answer_{i}": passed_items[i] for i in range(0, len(passed_items))} # dyanmically allocate to place them in the right columns
            dict_replacing = {'Questions': questions, **answers} # dictionary that will replace the forle create the new lines
            print(dict_replacing)
            df1 = pd.DataFrame(dict_replacing)
            df = df1
            passed_items = []
        else:
            passed_items.append(str(cell))

Y me devuelve:

{'Questions': 'Baggage policy', 'Answer_0': 'Baggage policy', 'Answer_1': 'Important consideration', 'Answer_2': 'Somewhat consider', 'Answer_3': 'Not an important consideration', 'Answer_4': 'Do not consider'}

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-142-2cb0448e0f0e> in <module>
      7             dict_replacing = {'Questions': questions, **answers} # dictionary that will replace the forle create the new lines
      8             print(dict_replacing)
----> 9             df1 = pd.DataFrame(dict_replacing)
     10             df = df1
     11             passed_items = []

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
    433             )
    434         elif isinstance(data, dict):
--> 435             mgr = init_dict(data, index, columns, dtype=dtype)
    436         elif isinstance(data, ma.MaskedArray):
    437             import numpy.ma.mrecords as mrecords

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals\construction.py in init_dict(data, index, columns, dtype)
    252             arr if not is_datetime64tz_dtype(arr) else arr.copy() for arr in arrays
    253         ]
--> 254     return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
    255 
    256 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals\construction.py in arrays_to_mgr(arrays, arr_names, index, columns, dtype)
     62     # figure out the index, if necessary
     63     if index is None:
---> 64         index = extract_index(arrays)
     65     else:
     66         index = ensure_index(index)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals\construction.py in extract_index(data)
    353 
    354         if not indexes and not raw_lengths:
--> 355             raise ValueError("If using all scalar values, you must pass an index")
    356 
    357         if have_series:

ValueError: If using all scalar values, you must pass an index

1 respuesta 1

0

Si quieres un Dataframe con esta fila, tienes que asignarle un índice con index=[0] (o el número que corresponda):

dict_replacing = {'Questions': 'Baggage policy', 'Answer_0': 'Baggage policy', 'Answer_1': 'Important consideration', 'Answer_2': 'Somewhat consider', 'Answer_3': 'Not an important consideration', 'Answer_4': 'Do not consider'}
df1 = pd.DataFrame(dict_replacing, index=[0])
df1
    Questions   Answer_0    Answer_1    Answer_2    Answer_3    Answer_4
0   Baggage policy  Baggage policy  Important consideration Somewhat consider   Not an important consideration  Do not consider

Por otro lado, estás pasando una serie, puedes usarlo así:

pd.Series(dict_replacing)
Questions                    Baggage policy
Answer_0                     Baggage policy
Answer_1            Important consideration
Answer_2                  Somewhat consider
Answer_3     Not an important consideration
Answer_4                    Do not consider

y si necesitas el DataFrame con esta columna usas to_frame():

pd.Series(dict_replacing).to_frame()
    0
Questions   Baggage policy
Answer_0    Baggage policy
Answer_1    Important consideration
Answer_2    Somewhat consider
Answer_3    Not an important consideration
Answer_4    Do not consider

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.