Setting values on a copy of a slice from a dataframe

Given a pandas dataframe, we have to set values on a copy of a slice from it.
Submitted by Pranit Sharma, on November 15, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Setting values on a copy of a slice from pandas DataFrame

We are given a DataFrame with two columns A and B and suppose we need to calculate the rolling mean for A so we will use the pandas.rolling_mean() method. This method will work and it will result in a column containing the expected elements but it will also generate a warning as described below.

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead.

This happens because our DataFrame is a copy of a slice. We can first create a proper copy of our DataFrame which will remove the warning and we will use the loc property of DataFrame along with the rolling mean method.

Let us understand with the help of an example,

Python code to set values on a copy of a slice from a dataframe

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {

# Creating DataFrame
df = pd.DataFrame(d)

# Display dataframe
print('Original DataFrame:\n',df,'\n')

# Making copy
df = df.copy()

# Calculating rolling mean
df.loc[:,'New'] = df['A'].rolling(3).mean()

# Display new DataFrame
print("New DF:\n",df)


Example: Setting values on a copy of a slice from a dataframe

Python Pandas Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.