Pandas - select lines

Asked

Viewed 5,572 times

2

Hello.

How do I select a specific line in a dataframe?

df1=pd.read_csv('arquivo1.csv', encoding='ISO-8859-1', sep=";")  

I’ve tried to do df.index[2], but gives error. The 2 is the line I want.

1 answer

4


Use the property loc.

For example, for the following CSV:

Year;Make;Model;Description;Price
1997;Ford;E350;"ac, abs, moon";3000.00
1999;Chevy;"Venture ""Extended Edition""";"";4900.00
1999;Chevy;"Venture ""Extended Edition; Very Large""";;5000.00
1996;Jeep;Grand Cherokee;"MUST SELL!
air, moon roof, loaded";4799.00

The following code prints the whole content and then only the third line (index 2):

import pandas as pd

df1 = pd.read_csv('teste.csv', encoding='ISO-8859-1', sep=";")
print('Tudo:\n', df1)

lin = df1.loc[2]
print('Linha 3:\n', lin)

Upshot:

>teste.py
Tudo:
    Year   Make                                   Model  \
0  1997   Ford                                    E350
1  1999  Chevy              Venture "Extended Edition"
2  1999  Chevy  Venture "Extended Edition; Very Large"
3  1996   Jeep                          Grand Cherokee

                            Description   Price
0                         ac, abs, moon  3000.0
1                                   NaN  4900.0
2                                   NaN  5000.0
3  MUST SELL!\r\nair, moon roof, loaded  4799.0
Linha 3:
 Year                                             1999
Make                                            Chevy
Model          Venture "Extended Edition; Very Large"
Description                                       NaN
Price                                            5000
Name: 2, dtype: object

Example CSV source: Wikipedia.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.