Reputation: 2014
My data are in a data frame. It looks like this.
I am trying to convert the data frame into the following format:
Currently I'm doing this conversion using the following Python codes, which are tedious.
def f(row):
if row['d1'] == 1:
return 1
if row['d1'] == 2:
return ''
if row['d1'] == 3:
return ''
if row['d1'] == 4:
return ''
else:
return ''
return np.nan
df['t1']=df.apply(f, axis=1)
Any help would be greatly appreciated.
Upvotes: 1
Views: 120
Reputation: 31662
You could apply following function:
def func(x):
x.iloc[x.iloc[0]] = 1
return x
In [66]: df
Out[66]:
d1 t1 t2 t3 t4 t5
0 5 0 0 0 0 0
1 1 0 0 0 0 0
2 3 0 0 0 0 0
3 4 0 0 0 0 0
4 1 0 0 0 0 0
5 2 0 0 0 0 0
In [67]: df.apply(func, axis=1)
Out[67]:
d1 t1 t2 t3 t4 t5
0 5 0 0 0 0 1
1 1 1 0 0 0 0
2 3 0 0 1 0 0
3 4 0 0 0 1 0
4 1 1 0 0 0 0
5 2 0 1 0 0 0
Upvotes: 5