Insert List into a Cell in Python Pandas Dataframe
Inserting a list into a specific cell in a pandas dataframe can be a tricky task. Let's explore the various approaches and potential issues based on the given example:
Original Problem:
A dataframe 'df' with the following structure:
A B 0 12 NaN 1 23 NaN
and a list 'abc' containing ['foo', 'bar']. The goal is to insert this list into cell 1B.
Efforts:
Solution:
The deprecated set_value method has been replaced with at. Using at guarantees setting a single value:
df.at[1, 'B'] = ['foo', 'bar']
Additional Considerations:
Updated Example:
Inserting the 'abc' list into df2.loc[1,'B'] and df3.loc[1,'B']:
df2 = pd.DataFrame({
'A': [12],
'B': [nan],
'C': ['bla']
})
df3 = pd.DataFrame({
'A': [12],
'B': [nan],
'C': ['bla bla'],
'D': [['item1', 'item2'], [11, 12, 13]]
})
df2.loc[1, 'B'] = ['foo', 'bar']
df3.loc[1, 'B'] = ['foo', 'bar']
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