0

I would like to add to my DF 4 new columns with boolean type representing quarters of the year. I have column with month numbers and would like to get this result:

month  Q1  Q2  Q3  Q4
    6   0   1   0   0
    7   0   0   1   0
    8   0   0   1   0
    9   0   0   1   0
   10   0   0   0   1
   11   0   0   0   1
   12   0   0   0   1
    1   1   0   0   0

At the moment I have tried this code:

print("Quarters")
quarters = {'Q1': [1, 2, 3], 'Q2': [4, 5, 6], 'Q3': [7, 8, 9], 'Q4': [10, 11, 12]}
for quarter, value in quarters.items():
    df_analysis[quarter] = (df_analysis["month"].isin(value))*1

Which works however I get following error: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame I have tried also:

df_analysis.loc[:, quarter] = (df_analysis.loc[:, "month"].isin(value))*1

However warning is still showing up. Could you please help how to write it correctly?

Veracious
  • 27
  • 4

1 Answers1

0

Do not loop, you should rather map and get_dummies:

quarters = {'Q1': [1, 2, 3], 'Q2': [4, 5, 6], 'Q3': [7, 8, 9], 'Q4': [10, 11, 12]}
# compute a better mapping format
d = {k:v for v,l in quarters.items() for k in l}
# {1: 'Q1', 2: 'Q1', 3: 'Q1', 4: 'Q2'...}

df.join(pd.get_dummies(df['month'].map(d)))

output:

   month  Q1  Q2  Q3  Q4
0      6   0   1   0   0
1      7   0   0   1   0
2      8   0   0   1   0
3      9   0   0   1   0
4     10   0   0   0   1
5     11   0   0   0   1
6     12   0   0   0   1
7      1   1   0   0   0
mozway
  • 194,879
  • 13
  • 39
  • 75
  • e.g. here is possible close dupe by `get_dummies` and dupe by `map` + flatten dicts. And it is wrong, because it is combinations. – jezrael Mar 30 '22 at 12:47
  • @jezrael well here the two cannot be used without the other, no? Also here you closed for the SettingWithCopyWarning while IMO this is not the real issue as the approach was wrong – mozway Mar 30 '22 at 12:48
  • yes, problem is something else like pointed dupe. – jezrael Mar 30 '22 at 12:49
  • However I still get the same warning: \lib\site-packages\pandas\core\frame.py:4174: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy errors=errors, – Veracious Mar 31 '22 at 14:13