Pandas Insert List into Cell of DataFrame

  • Post author:
  • Post category:Pandas
  • Post last modified:October 5, 2023

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.


# Below are some quick examples.

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

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

# 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(df)

Yields below output.


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

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.


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

Yields below output.


# Output:
   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

Pandas.DataFrame.astype() use to cast an object to a specified dtype. astype() function also convert 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(df)

Yields below output.


# Output:
   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].


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

Yields below output.


# Output:
   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(df)

Yields below output.


# Output:
   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)

6. 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

I am a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, I have honed my expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. My journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. I have started this SparkByExamples.com to share my experiences with the data as I come across. You can learn more about me at LinkedIn

Leave a Reply

You are currently viewing Pandas Insert List into Cell of DataFrame