haojie
haojie

Reputation: 753

Cannot get all the rows but can get all single row by using iloc?

Today I have faced an issue while using pandas. The problem is very simple, df.iloc[:][0] gives me such error.

  File "C:\workspaces\venv\lib\site-packages\pandas\core\frame.py", line 3805, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\workspaces\venv\lib\site-packages\pandas\core\indexes\base.py", line 3805, in get_loc
    raise KeyError(key) from err
  KeyError: 0

To check which row cannot using iloc. I tried the following

for i in range(content_df.shape[0]):
    try:
        df.iloc[i][0]
    except:
        print(i)

Here nothing prints at all!

One thing also makes me very surprised. I would like to using df.iloc[:][2:] to remove the first two columns. However, it removes the first two rows in this way.

Anyone knows why? Thanks in advance.

Upvotes: 0

Views: 45

Answers (2)

Pythoneer
Pythoneer

Reputation: 423

df.iloc[:, 2:] removes the first two columns

df.iloc[2:,:] or df.iloc[2:] removes the first two rows...

df.iloc[r:r, c:c]
         ^    ^
         |    |
slices rows   |
            slices columns

Upvotes: 1

sushant patil
sushant patil

Reputation: 18

  1. If you want to skip first two rows keeping all columns:

    df.iloc[2:, :]

  2. If you want to skip first two columns keeping all rows:

    df.iloc[:,2:]

Upvotes: 0

Related Questions