DKM
DKM

Reputation: 1801

Python Pandas: Append column names in each row

Is there a way to append column names in dataframe rows?

input:

cv  cv  mg  mg
5g  5g  0% zinsenzin

output:

cv  cv  col_name    mg    mg      col_name
5g  5g  cv          0% zinsenzin   mg

I tried by this, but it's not working

list_col = list(df)
for i in list_col:
    if i != i.shift(1)
    df['new_col'] = i

I got stuck here and can't find any solution.

Upvotes: 1

Views: 867

Answers (1)

jezrael
jezrael

Reputation: 862481

In pandas working with duplicated columns names is not easy, but possible:

c = 'cv cv mg mg sa sa ta ta at at ad ad an av av ar ar ai ai ca ca ch ch ks ks ct ct ce ce cw cw dt dt fr fr fs fs fm fm it it lg lg mk mk md md mt mt ob ob ph ph pb pb rt rt sz sz tg tg tt tt vv vv yq yq fr fr ms ms lp lp ts ts mv mv'.split()

df = pd.DataFrame([range(77)], columns=c)
print (df)
   cv  cv  mg  mg  sa  sa  ta  ta  at  at  ...  fr  fr  ms  ms  lp  lp  ts  \
0   0   1   2   3   4   5   6   7   8   9  ...  67  68  69  70  71  72  73   

   ts  mv  mv  
0  74  75  76  

[1 rows x 77 columns]

df = pd.concat([v.assign(new_col=k) for k, v in df.groupby(axis=1,level=0,sort=False)],axis=1)
print (df)
   cv  cv new_col  mg  mg new_col  sa  sa new_col  ta  ... new_col  lp  lp  \
0   0   1      cv   2   3      mg   4   5      sa   6  ...      ms  71  72   

  new_col  ts  ts new_col  mv  mv new_col  
0      lp  73  74      ts  75  76      mv  

[1 rows x 115 columns]

Upvotes: 2

Related Questions