Pandas unlock individual columns

Any sentence to postpone column=periodo_diawithout dropping a single column?

The original data frame is as follows:

|   | year | month | day | periodo_dia | valor_medida | Score_recogida |
|---|------|-------|-----|-------------|--------------|----------------|
| 0 | 2015 | 4     | 18  | manana      | 25.0         | 8.166667       |
| 1 | 2015 | 4     | 18  | noche       | 47.5         | 0.000000       |
| 2 | 2015 | 4     | 18  | tarde       | 20.0         | 0.000000       |
| 3 | 2015 | 4     | 19  | manana      | 0.0          | 0.000000       |
| 4 | 2015 | 4     | 19  | noche       | 0.0          | 4.066667       |

The desired data frame should look like this:

| year | month | day | manana | tarde | noche | valor_medida | Score_recogida |
|------|-------|-----|--------|-------|-------|--------------|----------------|
| 2015 | 4     | 18  | 1      | 0     | 0     | 25.0         | 8.166667       |
| 2015 | 4     | 18  | 0      | 0     | 1     | 47.5         | 0.000000       |
| 2015 | 4     | 18  | 0      | 1     | 0     | 20.0         | 0.000000       |
+4
source share
2 answers

You can use get_dummieswith astypeto convert values ​​to integer, dropand concat:

df1 = pd.get_dummies(df['periodo_dia']).astype(int)
print df1
   manana  noche  tarde
0       1      0      0
1       0      1      0
2       0      0      1
3       1      0      0
4       0      1      0

#drop column periodo_dia
df = df.drop('periodo_dia',axis=1)

print pd.concat([df, df1], axis=1)
   year  month  day  valor_medida  Score_recogida  manana  noche  tarde
0  2015      4   18          25.0        8.166667       1      0      0
1  2015      4   18          47.5        0.000000       0      1      0
2  2015      4   18          20.0        0.000000       0      0      1
3  2015      4   19           0.0        0.000000       1      0      0
4  2015      4   19           0.0        4.066667       0      1      0
+4
source

I hate answering my own question, but hope this helps others. This does the task:

df = pandas.concat([df.drop('periodo_dia',axis=1),
                    pandas.get_dummies(df['periodo_dia'])],axis=1)
0
source

All Articles