• Post author:
  • Post category:Pandas
  • Post last modified:March 27, 2024
  • Reading time:15 mins read
You are currently viewing Pandas Insert List into Cell of DataFrame

In pandas, you can insert a list into a cell of a DataFrame by assigning the list to the specified cell location. You can insert a list of values into a cell in Pandas DataFrame using DataFrame.at() ,DataFrame.iat(), and DataFrame.loc() methods. Each of these method takes different arguments. In this article, I will explain how to use insert the list into the cell by using these methods with examples.

1. Quick Examples of Insert List into Cell of DataFrame

If you are in a hurry, below are some quick examples of how to insert a list into single or multiple cells in DataFrame.


# Quick examples of insert list into cell of DataFrame

# Example 1: Insert list into cell 
# Using df.at()
df.at[1, 'Duration'] = ['30days', '35days']

# Example 2: Insert list index into cell 
# By using df.iat() method
df.iat[1, df.columns.get_loc('Duration')] = ['30days', '35days']

# Example 3: Get list index into cell 
# Using df.loc() attribute
df.loc[1, 'Duration'] = [['30days'], ['40days']]

Now, let’s create a pandas DataFrame with a few rows and columns, execute these examples, and validate results. Our DataFrame contains column names CoursesFeeDuration, and Discount.


# Create DataFrame
import pandas as pd

technologies = {
        'Courses':["Spark","PySpark","Python","pandas"],
        'Fee' :[20000,25000,22000,30000],
        'Duration':['30days','40days','35days','50days'],
        'Discount':[1000,2300,1200,2000]
               }
df = pd.DataFrame(technologies)
print("Create DataFrame:\n",df)

Yields below output.

pandas insert list into cell

2. Insert List into Cell Using DataFrame.at() Method

In order to insert the list into the cell will use DataFrame.at() function. For example, I will use the Duration column from the above DataFrame to insert list. at() inserts a list into a specific cell without raising a ValueError.

In the below example, the entire list ['30days','35days'] is treated as a single value and replaces the existing value in the cell at the intersection of the second row (index 1) and the ‘Duration’ column. This might not be the behavior you are expecting, as it effectively replaces the original value with a list.


# Insert list into cell using df.at()
df.at[1, 'Duration'] = ['30days', '35days']
print("DataFrame after insertion:\n",df)

Yields below output.

Pandas.DataFrame.astype() use to cast an object to a specified dtype. astype() function also converts any suitable existing column to type. Post update, change the column type to object.


# Insert list into cell 
# Using df.astype()
df.at[1,'Duration']=[30,35,40]
df['Duration']=df['Duration'].astype('object')
print("DataFrame after insertion:\n",df)

Yields below output.


# Output:
DataFrame after insertion:
    Courses    Fee      Duration  Discount
0    Spark  20000        30days      1000
1  PySpark  25000  [30, 35, 40]      2300
2   Python  22000        35days      1200
3   pandas  30000        50days      2000

3. Insert List Index into Cell by DataFrame.iat() Method

Pandas.DataFrame.iat() method is used to update data in a DataFrame for a specified location. The location is in the format [position in the row, position in the column]. For instance, used df.iat() to update the cell at the second row (1 index) and the ‘Duration’ column with the provided list ['30days','35days'].


# Insert list index into cell by df.iat() method
df.iat[1, df.columns.get_loc('Duration')] = ['30days', '35days']
print("DataFrame after insertion:\n",df)

Yields below output.


# Output:
DataFrame after insertion:
   Courses    Fee          Duration  Discount
0    Spark  20000            30days      1000
1  PySpark  25000  [30days, 35days]      2300
2   Python  22000            35days      1200
3   pandas  30000            50days      2000

4. List Index into Cell Using DataFrame.loc() Attribute

Pandas.DataFrame.loc() attribute can access a cell of rows and columns labels. By using this you can easily update the cell value with any value. In our case, will update with a list.


# Get list index into cell 
# Using df.loc() attribute
df.loc[1, 'Duration'] = [['30days'], ['40days']]
print("DataFrame after insertion:\n",df)

Yields below output.


# Output:
DataFrame after insertion:
   Courses    Fee          Duration  Discount
0    Spark  20000            30days      1000
1  PySpark  25000  [30days, 40days]      2300
2   Python  22000            35days      1200
3   pandas  30000            50days      2000

5. Complete Example to Insert List into Cell of Pandas DataFrame


import pandas as pd
    technologies = {
        'Courses':["Spark","PySpark","Python","pandas"],
        'Fee' :[20000,25000,22000,30000],
        'Duration':['30days','40days','35days','50days'],
        'Discount':[1000,2300,1200,2000]
               }
 df = pd.DataFrame(technologies)
 print(df)

# Insert list into cell using df.at().
df.at[1, 'Duration'] = ['30days', '35days']
print(df)

# Change the data type.
df['Duration']=df['Duration'].astype('object')
print(df)

# Insert list index into cell by df.iat() method.
df.iat[1, df.columns.get_loc('Duration')] = ['30days', '35days']
print(df)


# Get list index into cell using df.loc() attribute.
df.loc[1, 'Duration'] = [['30days'], ['40days']]
print(df)

Frequently Asked Questions on Pandas Insert List into Cell of DataFrame

How can I insert a list into a specific cell in a Pandas DataFrame?

To insert a list into a specific cell in a Pandas DataFrame, you can use the at method. For instance, example, df.at[1, 'Column2'] refers to the cell at the intersection of the second row and ‘Column2’. The list ['X', 'Y', 'Z'] is then assigned to this cell.

Can I use the iat method to insert a list into a cell?

The iat method is designed for scalar values, and directly inserting a list using iat may not work as expected. It’s more suitable for single values. For list insertion, consider using at or other methods like apply.

How can I append elements to an existing list in a DataFrame cell?

To append elements to an existing list in a DataFrame cell, you can use the apply method along with a lambda function.example, the elements [10, 11, 12] are appended to each list in the ‘Column1’. The apply method is used to apply the lambda function, which appends the elements to each existing list.

Is there any difference between using at and loc for list insertion?

Both at and loc can be used for list insertion, but at is designed for scalar values and is more efficient for single-value assignments. loc is more general and flexible but may have a slightly higher overhead. Choose the method that best fits your use case.

How can I insert a list into a cell based on a condition?

To insert a list into a cell based on a condition in a Pandas DataFrame, you can use boolean indexing. For example, the condition df['Column1'] == 2 creates a boolean mask where the values in ‘Column1’ are compared to 2. The list ['X', 'Y', 'Z'] is then inserted into the ‘Column2’ only where the condition is True.

Conclusion

By using df.at(), df.iat(), df.loc[] method you can insert a list of values into a pandas DataFrame cell. I have covered this here by using these functions with a sample DataFrame.

Reference

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium

Leave a Reply