상세 컨텐츠

본문 제목

Drop Rows from Pandas DataFrame

카테고리 없음

by Panda Kim 2022. 11. 21. 04:04

본문

Let's say you have a DataFrame of 3 animals like below.

The codes below create the DataFrame.

import pandas as pd

dict_zoo = {'Name' : ['Panda', 'Rabbit', 'Lion'],
           'Food' : ['Bamboo', 'Carrot', 'Meat'],
           'Age' : [5,2,7],
           'Species' : ['Mammals', 'Mammals', 'Mammals']}

df_zoo = pd.DataFrame(dict_zoo)

If you want to delete the 1st row from the DataFrame,

use .drop() method like below.


df_zoo.drop(1, axis = 0)

For the first argument of the .drop() method, the index value should be put in.

If the argument axis is set 0 you drop row, and if it is set 1 you drop column.


Even if the index values are string not numeric,

you can still drop rows by the index name.

Below is the codes for creating the DataFrame whose index are A, B, C.

dict_zoo = {'Name' : ['Panda', 'Rabbit', 'Lion'],
           'Food' : ['Bamboo', 'Carrot', 'Meat'],
           'Age' : [5,2,7],
           }

df_zoo = pd.DataFrame(dict_zoo)
df_zoo = df_zoo.rename(index = {0 : 'A', 1 : 'B', 2 : 'C'})

In order to drop the same row,

use the same .drop() method.

df_zoo.drop('B', axis = 0)

 

댓글 영역