Home > Backend Development > Python Tutorial > How to Insert Lists into Pandas DataFrame Cells Without Errors?

How to Insert Lists into Pandas DataFrame Cells Without Errors?

Linda Hamilton
Release: 2024-11-02 08:50:29
Original
796 people have browsed it

How to Insert Lists into Pandas DataFrame Cells Without Errors?

Inserting Lists into Pandas Cells

Problem

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']
Copy after login

The following attempts to insert the abc list into 1B, but they produce errors or incorrect insertion:

  1. df.ix[1,'B'] = abc - Error: Must have equal len keys and value when setting with an iterable
  2. df.ix[1,'B'] = [abc] - Inserts a list with one element: [['foo', 'bar']]
  3. df.ix[1,'B'] = ', '.join(abc) - Inserts a string: "foo, bar"
  4. df.ix[1,'B'] = [', '.join(abc)] - Inserts a list with one element: ['foo, bar']

Solution

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']
Copy after login

This will insert the abc list into 1B as expected:

    A  B
0  12  NaN
1  23  ['foo', 'bar']
Copy after login

Note that the DataFrame column must have dtype=object to allow list insertion. For example:

df['B'] = df['B'].astype('object')
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template