Álvaro V.
Álvaro V.

Reputation: 39

Warning message on "SettingWithCopyWarning"

I'm trying an exercise from a DataQuest proyect, and when creating a 'month' column from a datetime variable, to aggregate values, I get a warning message that I don't know how to use to fix my code (I've read something about this warning message, but didn't find the connection with my code).

My piece of code:

#Create a new column containing the month
daytime_data['month'] = daytime_data['date_time'].dt.month

#Aggregate the data and avearge it by month
by_month = daytime_data.groupby('month').mean()
print(by_month['traffic_volume'])

The warning message:

C:\Users\Alvaro\AppData\Local\Temp/ipykernel_4856/2147418321.py:2: SettingWithCopyWarning: 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 See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy daytime_data['month'] = daytime_data['date_time'].dt.month

Could you please help me find what should I fix in my code?

Upvotes: 0

Views: 239

Answers (1)

Waleed Alfaris
Waleed Alfaris

Reputation: 155

The answer is in your warning message. to remove this error simply change the

daytime_data['month'] = daytime_data['date_time'].dt.month

into

daytime_data.loc[:, 'month'] = daytime_data['date_time'].dt.month

Upvotes: 1

Related Questions