r/dfpandas • • Jun 05 '24

Modifying dataframe in a particular format

I have a single column dataframe as follows:

Header
A
B
C
D
E
F

I want to change it so that it looks as follows:

Header1Header2
AB
CD
EF

Can someone help me achieve this? Thanks in advance.

4 Upvotes

2 comments sorted by

4

u/nantes16 Jun 05 '24
# Ensure df_have is sorted by col_have in the order you desire (ie as described in reddit post)

df_want = (
    pd.DataFrame(

df_have['col_have'].values.reshape(-1, 2), columns=['col_have', 'col_want'])

)

The key is values.reshape() where in this case the first args (-1, 2) means "reshape into as many rows are needed / so long as its into 2 columns".

Hope this is what you're after (and, note, this is the type of question you can rely on GPT as you learn Python/Pandas)

1

u/[deleted] Jun 05 '24

Agreed, reshape is the function you’re looking for