I am trying to add a new TimeZone column (according to the country code, such as 'UK'). I am doing it in a loop, going through each country code. (I realize there must be a way to do it with one line, without looping. But my actual usecase is much more complex).
I'm getting that dreaded warning in pandas - SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
I'm not sure what I should do in a different way.
fb.data['tz'] = ""
for country in fb.data['Country'].unique():
TARGET_TZ = tzh.code_to_single_tz[country] if country != 'missing_value' else 'UTC'
country_index = fb.data['Country'] == country
fb.data['tz'][country_index] = TARGET_TZ
If you are interested in the full use case - I'm also converting a UTC datetime to the "local" time in a new column (and therefore getting the warning twice, for tz
and for install_datetime_in_tz
:
tzh = TimezonesHelper()
fb.data['install_datetime_in_tz'] = ""
fb.data['tz'] = ""
fb.data['install_datetime_in_tz'] = fb.data['install_datetime_in_tz'].astype('datetime64')
for country in fb.data['Country'].unique():
TARGET_TZ = tzh.code_to_single_tz[country] if country != 'missing_value' else 'UTC'
country_index = fb.data['Country'] == country
fb.data['install_datetime_in_tz'][country_index] = fb.data['install_date'][country_index].dt.tz_localize('UTC').dt.tz_convert(TARGET_TZ).dt.tz_localize(None)
fb.data['tz'][country_index] = TARGET_TZ