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