I'm looking for a more elegant and Pythonic code for the following problem:
In column start I have a release week for every item (from 1 to 4), I add W1,..., W4 columns with ones.
Next I want to update columns in this way (basically, replace the ones in the release week and the week before and week after with zeros):
start W1 W2 W3 W4
1 0 0 1 1
2 0 0 0 1
3 1 0 0 0
4 1 1 0 0
I'm doing it right now with this:
import pandas as pd
data = {'start': [1,2,3,4]}
df = pd.DataFrame(data)
for i in range(1,4+1):
df['W'+str(i)] = 1
for index, i in enumerate(df['start']):
if i==1:
df.ix[index, 'W1'] = 0
df.ix[index, 'W2'] = 0
elif i==4:
df.ix[index, 'W3'] = 0
df.ix[index, 'W4'] = 0
else:
df.ix[index, 'W'+str(i-1)] = 0
df.ix[index, 'W'+str(i)] = 0
df.ix[index, 'W'+str(i+1)] = 0
mapis slower. Did my answer not work for you?