append column values to row pandas

Viewed 354
df = pd.DataFrame()
df['col1'] = ('y','y','y')
df['col2'] = ('a','b','c')
df['col3'] = ('x','x','x')
print df

I have this df and am trying to copy or move the b,c to new columns in row one. I've tried pivot_table, pd.groupby, and for index, row in top.iterrows():

But there may not always be three rows in the df. So if there aren't any rows then don't do anything.

This has been my last attempt. I don't remember exactly what I tried with .groupby or pivot_table

for index, row in df.iterrows():
    df1['col2'+row] = df1['col2'][row]
    top_comb = top_comb.append(top)

Col1 | Col2 | Col3 | Col21 | Col22 
 y   |   a  |  x   |  b    |   c  
2 Answers

If you'd like your output to be a single row, you can do the following:

if len(df) > 1:
    new_df = df.col2.loc[1:].to_frame().T.reset_index(drop=True)
    new_df.columns = [f'col2{i+1}' for i in range(len(new_df.columns))]
    pd.concat([df.loc[0, :].to_frame().T, new_df], axis=1)


  col1 col2 col3 col21 col22
0    y    a    x     b     c

TRY:

df1 = df.groupby(['col1', 'col3'], as_index=False).agg(list)
df = pd.concat([df1, df1.pop('col2').apply(pd.Series).add_prefix('col2')], 1)
Related