0

I need to write a function called read_data that reads the iris dataset. The columns are in this order:

Column 1
Column 2
Column 3
Column 4
Column 5

The columns need to be returned in the following order:

Column 1
Column 3
Column 2
Column 4
Column 5

I tried

def read(file_path):
    file_path = './file.csv'
    with open (file_path, 'r') as fin:
        for row in fin:
            print(row)

How to change the order of the columns?

Yeet
  • 19
  • 1
  • 4
  • 1
    Please format your code so that it is readable. Also, `pandas` has some nice CSV utilities that may make your job easier – Andrew Fan Jun 26 '19 at 00:54
  • 2
    Python comes with a _built-in_ [`csv`](https://docs.python.org/3/library/csv.html#module-csv) module, that should make it relatively easy to do what you want. – martineau Jun 26 '19 at 01:00

2 Answers2

1

You can assign the csv file to a dataframe:

import pandas as pd

df = pd.read_csv("iris.csv")

#Then you can rearrange the elements in the list how you want

df = df[['Column1', 'Column2', 'Column3']]

df.to_csv("iris.csv")

Hope this helps.

Integraty_dev
  • 500
  • 3
  • 18
ferdbugs
  • 19
  • 5
1

There can be different approaches depending on what you want to do. Here is another answer that shows how to switch columns when writing

Here is another really simple solution - it doesn't really on any other modules, but there may be easier solutions depending on what you are looking for. Alter you function like this:

for row in fin:
    cols = row.split(",")
    desired_order=[0,2,1,3,4]
    new_row = ""
    for num in desired_order:
        new_row += cols[num]
        new_row += ","
    print(new_row)

test input

1,2,3,4,5,
6,7,8,9,10

produces

1,3,2,4,5,
6,8,7,9,10,
grizzasd
  • 363
  • 3
  • 15