1

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.

3
  • Padraic, I edited my post. Is this what you need? Commented Dec 14, 2015 at 19:33
  • Hi Kevin, Could you please explain what df['t1']=df.apply(f, axis=1) does? Commented Dec 14, 2015 at 19:45
  • It read the value in d1 column and insert "1" into t1 column (if the value in d1 is 1). My code is poor. That's why I was looking for better codes. Commented Dec 14, 2015 at 19:49

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

You're awesome! Thanks a lot!
I'm glad I was able to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.