juanjo
juanjo

Reputation: 57

Python, Pandas create column based on value of index

I have a dataframe that looks like the below. What I'd like to do is create another column that is based on the VALUE of the index (so anything less the 10 would have another column and be labeled as "0"). I tried with:

df['Disp'] = '0'
df['Disp'][df.index < 10] = '1'

but i get the error "SettingWithCopyWarning:"

df = pd.DataFrame({ 'Hora': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
                    'EUGE': ['RE','RE','RE','RE','RE','RE','RE','RE','RE','RE','RE','RE','RE','RE','RE'], 
                    'Tipo_Dato': ['DM','DM','DM','DS','DS','DS','DM','DS','DS','DM','DM','DM','DS','DM','DM']})

i should get:

     Hora EUGE Tipo_Dato  Disp
0      1   RE        DM     0
1      2   RE        DM     0
2      3   RE        DM     0
3      4   RE        DS     0
4      5   RE        DS     0
5      6   RE        DS     0
6      7   RE        DM     0
7      8   RE        DS     0
8      9   RE        DS     0
9     10   RE        DM     0
10    11   RE        DM     1
11    12   RE        DM     1
12    13   RE        DS     1
13    14   RE        DM     1

Upvotes: 0

Views: 123

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

You can do it this way:

df['Dist'] = (df.index >= 10 ).astype(int)

Output:

    Hora EUGE Tipo_Dato  Dist
0      1   RE        DM     0
1      2   RE        DM     0
2      3   RE        DM     0
3      4   RE        DS     0
4      5   RE        DS     0
5      6   RE        DS     0
6      7   RE        DM     0
7      8   RE        DS     0
8      9   RE        DS     0
9     10   RE        DM     0
10    11   RE        DM     1
11    12   RE        DM     1
12    13   RE        DS     1
13    14   RE        DM     1
14    15   RE        DM     1

Depending on how df was originally created this will work, if you create df, by slicing a bigger dataframe, then you can use df_larger = df[condition].copy() to prevent the 'SettingWithCopy' warning message. This is not an error, just a warning that your changes to df may not propagate back up to df_larger.

Upvotes: 1

rhug123
rhug123

Reputation: 8768

You could also use assign to return a copy of the dataframe.

df.assign(Disp = np.where(df.index<10,1,0))

Upvotes: 0

Related Questions