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:
<code class="python">df.at[1, 'B'] = ['foo', 'bar']</code>
Additional Considerations:
Updated Example:
Inserting the 'abc' list into df2.loc[1,'B'] and df3.loc[1,'B']:
<code class="python">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']</code>
The above is the detailed content of How Can I Insert a List into a Specific Cell in a Python Pandas Dataframe?. For more information, please follow other related articles on the PHP Chinese website!