Home »
Python »
Python Programs
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.
Problem statement
Given a pandas dataframe, we have to set values on a copy of a slice from it.
Setting values on a copy of a slice from pandas DataFrame
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 program 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 = {
'A':[1,2,3,4,5],
'B':[6,7,8,9,10]
}
# 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)
Output
The output of the above program is:
Python Pandas Programs »