1

Given a small dataset as follows, say for each city there are two entries:

  city  price  quantity
0   bj  10104      5934
1   bj   5423       623
2   sh  15728      9105
3   sh    533        76
4   gz   4012      3558
5   gz    523      7632
6   sz   3770      1946
7   sz   6237      7364

I want to split this dataset into two based on the following logic: the first entry of all the cities to be df1, which index are 0, 2, 4, 6 and the second entry of all the cities to be df2, which index are 1, 3, 5, 7.

The final results will like this:

df1:

  city  price  quantity
0   bj  10104      5934
2   sh  15728      9105
4   gz   4012      3558
6   sz   3770      1946

df2:

  city  price  quantity
1   bj   5423       623
3   sh    533        76
5   gz    523      7632
7   sz   6237      7364

How could I do that in Pandas? Thanks.

1 Answer 1

3

You can select pair and unpair rows by indexing:

df1 = df.iloc[::2]
print (df1)
  city  price  quantity
0   bj  10104      5934
2   sh  15728      9105
4   gz   4012      3558
6   sz   3770      1946

df2 = df.iloc[1::2]
print (df2)
  city  price  quantity
1   bj   5423       623
3   sh    533        76
5   gz    523      7632
7   sz   6237      7364
Sign up to request clarification or add additional context in comments.

1 Comment

You can achieve the same using loc too

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.