Home > Article > Backend Development > How to Insert Lists into Pandas DataFrame Cells Without Errors?
In Python, attempting to insert a list into a cell of a Pandas DataFrame can result in errors or unexpected results. For example, when trying to insert a list into cell 1B of a DataFrame df:
df = pd.DataFrame({'A': [12, 23], 'B': [np.nan, np.nan]}) abc = ['foo', 'bar']
The following attempts to insert the abc list into 1B, but they produce errors or incorrect insertion:
To insert lists into cells of a DataFrame without errors, use the at method, which always refers to a single value:
df.at[1, 'B'] = ['foo', 'bar']
This will insert the abc list into 1B as expected:
A B 0 12 NaN 1 23 ['foo', 'bar']
Note that the DataFrame column must have dtype=object to allow list insertion. For example:
df['B'] = df['B'].astype('object')
The above is the detailed content of How to Insert Lists into Pandas DataFrame Cells Without Errors?. For more information, please follow other related articles on the PHP Chinese website!