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')
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3