-1

I have a dataset and I want to combine the first two rows of the same dataset into a single dataset. The original dataset is very big but I have mentioned a small example here.

df

  one  two  three
0  T    H     A
1  N    K     S
2  F    O     R
3  H    L     P  

After combining the first two rows it should look like this:

df

  one  two  three  one  two  three
0  T    H     A     N    K     S

I'm very new to StackOverflow and started my career recently in python. If my question is not formatted correctly please suggest edits. Thanks.

Jee
  • 969
  • 1
  • 7
  • 26
Komali
  • 45
  • 5
  • Please place the question in the actual body of your post. It makes it easier for users to actually understand what you are looking for. – Jee Sep 27 '20 at 19:43

1 Answers1

0

You can use df.iloc to get two slices of the dataframe one for even rows and another for odd rows. Then pd.concat(..., axis=1) to get them back together.

Notice pd.concat will try to align the input dataframes on their index (i.e. 0, 1, 2, 3) and if one of the dataframes does not have data for a particular index then it will fill with null values. So we need reset_index to get the desired output.

df = pd.concat(
    [
        df.iloc[::2].reset_index(drop=True),
        df.iloc[1::2].reset_index(drop=True)
    ], axis=1
)

Output

  one two three one two three
0   T   H     A   N   K     S
1   F   O     R   H   L     P

You can read more about pd.concat in this answer and of course the user guide

RichieV
  • 5,103
  • 2
  • 11
  • 24