kevin
kevin

Reputation: 2014

Converting a data frame - Python

My data are in a data frame. It looks like this.

enter image description here

I am trying to convert the data frame into the following format:

enter image description here

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

Answers (1)

Anton Protopopov
Anton Protopopov

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

Related Questions