2

I splited a dataframe into two parts and changed their column names seperately. Here's what I got:

df1 = df[df['colname'==0]]
df2 = df[df['colname'==1]]
df1.columns = [ 'a'+ x for x in df1.columns]
df2.columns = [ 'b'+ x for x in df2.columns]

And it turned out df2 has the columns start with 'ba' rather than 'b'. What happened?

1
  • Do you think df1 = df[df['colname']==0] and df2 = df[df['colname']==1] ? For me your solution working nice.
    – jezrael
    Commented May 13, 2018 at 6:58

1 Answer 1

1

I cannot simulate your problem, for me working nice.

Alternative solution should be add_prefix instead list comprehension:

df = pd.DataFrame({'colname':[0,1,0,0,0,1],
                   'C':[7,8,9,4,2,3],
                   'D':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'F':list('aaabbb')})

print (df)
   C  D  E  F  colname
0  7  1  5  a        0
1  8  3  3  a        1
2  9  5  6  a        0
3  4  7  9  b        0
4  2  1  2  b        0
5  3  0  4  b        1

df1 = df[df['colname']==0].add_prefix('a')
df2 = df[df['colname']==1].add_prefix('b')
print (df1)
   aC  aD  aE aF  acolname
0   7   1   5  a         0
2   9   5   6  a         0
3   4   7   9  b         0
4   2   1   2  b         0

print (df2)
   bC  bD  bE bF  bcolname
1   8   3   3  a         1
5   3   0   4  b         1
2
  • Thx! add_prefix works for me. But what actually went wrong for the list comprehension?
    – Ethan.cy
    Commented May 13, 2018 at 7:10
  • @Ethan.cy - it is not bad, for me working nice too. Only I use built pandas function as alternative.
    – jezrael
    Commented May 13, 2018 at 7:11

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.