Why I'm I getting this? cont = response.choices[0].message.content outdf.loc[index,…
- User
Why I'm I getting this?
cont = response.choices[0].message.content out_df.loc[index, "aspects"] = (list(ast.literal_eval(cont).keys()))
Traceback (most recent call last): File "/snap/pycharm-professional/506/plugins/python-ce/helpers/pydev/pydevd.py", line 1570, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "/snap/pycharm-professional/506/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/XXXprompt_llm.py", line 20, in direct_mentions_main(args.fname, File "/home/esther/PycharmProjects/edut710/holocaust_mentions/prompting/prompt_gpt.py", line 146, in direct_mentions_main general_prompt_pipeline(fname, model_k=model_k, prompt_k=prompt_k, system_prompt=system_prompt,input_col=input_col, out_col=out_col) File "/home/esther/PycharmProjects/edut710/holocaust_mentions/prompting/prompt_gpt.py", line 223, in general_prompt_pipeline out_df.loc[index, "aspects"] = list(ast.literal_eval(cont).keys()) File "/XXX.10/site-packages/pandas/core/indexing.py", line 849, in setitem iloc._setitem_with_indexer(indexer, value, self.name) File "/XXX.10/site-packages/pandas/core/indexing.py", line 1791, in _setitem_with_indexer self._setitem_with_indexer(new_indexer, value, name) File "/XXX.10/site-packages/pandas/core/indexing.py", line 1835, in _setitem_with_indexer self._setitem_with_indexer_split_path(indexer, value, name) File "/XXX.10/site-packages/pandas/core/indexing.py", line 1891, in _setitem_with_indexer_split_path raise ValueError( ValueError: Must have equal len keys and value when setting with an iterable
- Assistant
pandas is complaining because the thing on the right-hand side is an iterable (a list) while the thing you’re assigning to with .loc[index, "aspects"] is not a single scalar cell (most likely index is selecting more than one row). When you assign an iterable to multiple rows, pandas expects the iterable length to match the number of selected rows. It doesn’t, so you get:
ValueError: Must have equal len keys and value when setting with an iterable
What’s probably happening
index isn’t a single label (e.g., it’s a list/array/boolean mask/slice), so out_df.loc[index, "aspects"] returns many rows in that single column.
- User
How to add a list or tuple as a cell in a df?
- Assistant
In pandas, you can store a list or tuple inside a single cell (as an object) because DataFrame cells can hold arbitrary Python objects. Ways to add a list or tuple into a DataFrame cell
- Assign directly to a single cell pythonCopyEditimport pandas as pd
df = pd.DataFrame({"col1": [1, 2, 3]}) df.at[0, "col1"] = [1, 2, 3] # Store a list in the cell df.at[1, "col1"] = (4, 5, 6) # Store a tuple print(df)
-
When creating the DataFrame pythonCopyEditdf = pd.DataFrame({ "col1": [[1, 2, 3], [4, 5], [6, 7, 8]], "col2": [10, 20, 30] })
-
Append rows with lists pythonCopyEditdf = pd.DataFrame(columns=["col1", "col2"]) df.loc[0] = [[1, 2, 3], "A"] df.loc[1] = [(4, 5), "B"]
Important Notes
Pandas stores lists/tuples as Python objects in the cell (dtype becomes object).
If you need to store lists, ensure the column is not a numpy array column (since numpy enforces fixed dimensions).
To check: pythonCopyEditdf.dtypes
Example with your case To store list(ast.literal_eval(cont).keys()) in a single cell: pythonCopyEditout_df.at[index, "aspects"] = list(ast.literal_eval(cont).keys())
- User
I get this:
Traceback (most recent call last): File "/snap/pycharm-professional/506/plugins/python-ce/helpers/pydev/pydevd.py", line 1570, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "/snap/pycharm-professional/506/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/XXXprompt_llm.py", line 20, in direct_mentions_main(args.fname, File "/home/esther/PycharmProjects/edut710/holocaust_mentions/prompting/prompt_gpt.py", line 147, in direct_mentions_main general_prompt_pipeline(fname, model_k=model_k, prompt_k=prompt_k, system_prompt=system_prompt, input_col=input_col, File "/home/esther/PycharmProjects/edut710/holocaust_mentions/prompting/prompt_gpt.py", line 227, in general_prompt_pipeline out_df.loc[index, "aspects"] = list(ast.literal_eval(cont).keys()) File "/XXX.10/site-packages/pandas/core/indexing.py", line 849, in setitem iloc._setitem_with_indexer(indexer, value, self.name) File "/XXX.10/site-packages/pandas/core/indexing.py", line 1835, in _setitem_with_indexer self._setitem_with_indexer_split_path(indexer, value, name) File "/XXX.10/site-packages/pandas/core/indexing.py", line 1891, in _setitem_with_indexer_split_path raise ValueError( ValueError: Must have equal len keys and value when setting with an iterable
- Assistant
You’re still getting this error because out_df.loc[index, "aspects"] is selecting multiple rows, and pandas is interpreting the list on the right-hand side as a set of values to broadcast across these rows. How to fix this To store a list (or tuple) in a single DataFrame cell, you must ensure that your selection points to exactly one row. Use .at instead of .loc: pythonCopyEditout_df.at[index, "aspects"] = list(ast.literal_eval(cont).keys())
Why .loc Fails Here
loc[index, "aspects"] can return a Series if index is a list, slice, or boolean mask.
When pandas tries to assign [1,2,3] to multiple rows, it expects [1,2,3] to match the number of rows.
at is specifically for scalar row/column access, so it doesn’t try to match lengths — it just sets the value.
If index can be multiple rows but you want the same list in each row You can do: pythonCopyEditkeys = list(ast.literal_eval(cont).keys()) out_df.loc[index, "aspects"] = [keys] * len(out_df.loc[index])
If you are unsure whether index is a single value Force it to store the list as an object: pythonCopyEditkeys = list(ast.literal_eval(cont).keys())
- User
index is meant to be a single row
- Assistant
If index is meant to be a single row, then the error strongly suggests that index is not a scalar (e.g., 0, 1, 'row_name') but rather a list, array, or something like [0].
The Fix Use .at instead of .loc: pythonCopyEditout_df.at[index, "aspects"] = list(ast.literal_eval(cont).keys())
Check the Type of index To confirm: pythonCopyEditprint(f"Index type: {type(index)}, value: {index}")
If you see something like <class 'list'> or <class 'numpy.int64'> wrapped in an array, you need to extract the scalar: pythonCopyEditif isinstance(index, (list, tuple, pd.Index)): index = index[0] # take the first element
Safer Code You can ensure it's always a single row assignment with: pythonCopyEditkeys = list(ast.literal_eval(cont).keys()) out_df.at[int(index), "aspects"] = keys
(if index is numeric)
Would you like me to give you a helper function like set_cell(df, row_index, col, value) that guarantees correct scalar assignment even if row_index accidentally comes as a list?
- User
print(f"Index type: {type(index)}, value: {index}") PyDev console: using IPython 8.31.0 Index type: <class 'str'>, value: 00049_8
- Assistant
Ah, now we see the issue: index is a string ("00049_8"), not an integer. When you do: pythonCopyEditout_df.loc[index, "aspects"] = list(ast.literal_eval(cont).keys())
pandas interprets "00049_8" as a label for rows in the index. If your DataFrame’s index is not strings but numbers (0, 1, 2,...), then loc["00049_8"] returns multiple rows (or none, which might cause pandas to fallback in weird ways).
Fix 1: Use .at with string index If "00049_8" is actually an index label in your DataFrame: pythonCopyEditout_df.at["00049_8", "aspects"] = list(ast.literal_eval(cont).keys())
Fix 2: If your DataFrame index is numeric If out_df.index is integers (0, 1, 2,...), but index is a string (e.g., row ID in another column), you need to find its row position first: pythonCopyEditrow_idx = out_df.index[out_df['some_id_col'] == index][0] out_df.at[row_idx, "aspects"] = list(ast.literal_eval(cont).keys())
Debugging Tip Check what out_df.loc[index] returns: pythonCopyEditprint(out_df.loc[index]) # See if it returns a single row or error
Want me to rewrite your problematic line into a safe, 3-line snippet that automatically handles both string and numeric indices and ensures you’re only writing to one row?
- User
out_df.at[index, "aspects"] = list(ast.literal_eval(cont).keys()) TypeError: float() argument must be a string or a real number, not 'list' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/XXX.10/site-packages/pandas/core/frame.py", line 4181, in _set_value self._mgr.column_setitem(icol, iindex, value, inplace_only=True) File "/XXX.10/site-packages/pandas/core/internals/managers.py", line 1382, in column_setitem col_mgr.setitem_inplace(idx, value) File "/XXX.10/site-packages/pandas/core/internals/managers.py", line 2042, in setitem_inplace super().setitem_inplace(indexer, value) File "/XXX.10/site-packages/pandas/core/internals/base.py", line 193, in setitem_inplace arr[indexer] = value ValueError: setting an array element with a sequence. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/XXX.10/site-packages/IPython/core/interactiveshell.py", line 3577, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in out_df.at[index, "aspects"] = list(ast.literal_eval(cont).keys()) File "/XXX.10/site-packages/pandas/core/indexing.py", line 2430, in return super().(key, value) File "/XXX.10/site-packages/pandas/core/indexing.py", line 2386, in self.obj._set_value(*key, value=value, takeable=self._takeable) File "/XXX.10/site-packages/pandas/core/frame.py", line 4193, in _set_value self.loc[index, col] = value File "/XXX.10/site-packages/pandas/core/indexing.py", line 849, in iloc._setitem_with_indexer(indexer, value, self.name) File "/XXX.10/site-packages/pandas/core/indexing.py", line 1835, in _setitem_with_indexer self._setitem_with_indexer_split_path(indexer, value, name) File "/XXX.10/site-packages/pandas/core/indexing.py", line 1891, in _setitem_with_indexer_split_path raise ValueError( ValueError: Must have equal len keys and value when setting with an iterable
- Assistant
This error means pandas is trying to treat your list as a sequence of values to broadcast into multiple cells, which suggests that the "aspects" column isn't set up to store Python objects (lists). Pandas is assuming it should store numeric data and is rejecting the list.
Solution: Make the column object type Before assigning, explicitly create or convert the column to object type: pythonCopyEditif "aspects" not in out_df.columns: out_df["aspects"] = None # create the column
out_df["aspects"] = out_df["aspects"].astype(object) out_df.at[index, "aspects"] = list(ast.literal_eval(cont).keys())
This ensures pandas knows the cell can store arbitrary Python objects like lists or tuples.
Why this fixes it
By default, if a column doesn't exist, pandas might try to insert a column with numeric dtype.
list values cannot be coerced into a float or int.
astype(object) makes pandas treat cells like Python objects (no type enforcement), allowing lists to be stored.
Debugging Step Check the column type before assigning: pythonCopyEditprint(out_df.dtypes)
If aspects is float64 or any numeric type, you must convert it to object.