0

I am trying to retrieve the rows and columns of a csv file using python. But I am unable to do so. My code is:

import pandas as pd
data = pd.read_csv("data1.csv", nrows=1)
print(data)

This code prints the column name and the first row values. However, I want to display only specific columns and its respective row values.

Fanatique
  • 431
  • 3
  • 13
  • Possible duplicate of [How do I read and write CSV files with Python?](https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – sɐunıɔןɐqɐp Jul 04 '18 at 09:27

1 Answers1

2
import pandas as pd
data = pd.read_csv("data1.csv", nrows=1)
print(data)

A couple of things first: * You have passed a kwargnrows=1. This means you have only read the first row. If you take that out, you will get all the rows.

  • When you use pandas, you get a data frame.

  • Once you have thedataframe, you can extract the wanted columns like so:

    selected_data = data[[‘column_name1’, ‘column_name2’]]

  • You can also use a more numeric column index syntax like so:

    selected_data = data.iloc[:,1:4]

Where you select all the rows :, and column index 1 up to butnot including 4, 1:4

Khanal
  • 788
  • 6
  • 14