2

I want to ask you, How to select rows that have the same index number in a DataFrame. Example:

df=

  A, B, C,
0 1. 2. 1.
1 2. 2. 2. 
2 2. 2. 2. 
3 3. 3. 4.
  A, B, C,
0 1. 2. 1.
1 2. 2. 2. 
2 2. 2. 0. 
3 3. 3. 4.
  A, B, C,
0 1. 2. 1.
1 2. 2. 2. 
2 0. 2. 2. 
3 3. 3. 4.

I expect:

df1=

   A, B, C,
 2 2. 2. 2. 
 2 2. 2. 0. 
 2 0. 2. 2. 

I'm using df.loc[2] but only shows me the first set of data. Also used df1=df.set_index(['2']) and doesn't works too. Thanks in advance!

4
  • 1
    You can't have duplicates in your index. Commented May 12, 2017 at 23:19
  • 1
    can you paste output of df.index and df.columns Commented May 12, 2017 at 23:20
  • Is wear, my df.index= Out[101]: RangeIndex(start=0, stop=874, step=1) but I can see index of variable length [1,2,3,4,5,,1,2,3,,1,2,3...] and the output of my columns is: Index(['Unnamed: 0', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34' Commented May 12, 2017 at 23:31
  • Can you paste sample input and sample output and the code , what attempts you have made so far at solving the problem? Commented May 12, 2017 at 23:58

2 Answers 2

2

The index may have duplicates. Especially, when you concatenate different data frames. Use this to filter data based on your index:

df1 = df[df.index==2]
Sign up to request clarification or add additional context in comments.

Comments

1

Looks like you need to group by the index values:

df1 = df.groupby(df.index).get_group(2)
df1
#   A  B  C
#2  2  2  2
#2  2  2  0
#2  0  2  2

2 Comments

does not work for me! with that I only get the first
Please update the original question to include the correct definition of df (they way it is typed now, it is not a valid Pandas dataframe; I assumed that it had 12 rows, three columns A, B, and C, and a repeated index).

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.