1

I know that I can load the datasets in the pandas using the read_csv function of pandas as below

import pandas as pd

df = read_csv('/home/user/iris_dataset.csv', header=0)
df.head()

How can I load the same dataset using the command line arguments while executing the code ? I want to load the dataset to a data frame like python3 example.py -D 'iris_dataset.csv' while executing the code

1 Answer 1

1

Using sys.argv

We can use sys.argv like so :

import pandas as pd
import sys

  
df = pd.read_csv(f'/home/user/{sys.argv[1]}', header=0)
print(df.head())

We can call it using :

python example.py iris_dataset.csv

Using argparse

Or we can use argparse :

import argparse
import pandas as pd

my_parser = argparse.ArgumentParser()
my_parser.add_argument('-D', action='store', type=str, required=True)
args = my_parser.parse_args()

df = pd.read_csv(f'/home/user/{args.D}', header=0)
print(df.head())

It works correctly using :

python example.py -D "iris_dataset.csv"
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for answer, I wanted to know if it can be done with argparse module as an alternative solution ?
Yes we can indeed, I updated the answer for you :) Hope it helps !
Glad it works ! As it does, don't hesitate to validate the answer and even upvote it ;) To answer your additional query, you have two possibilities : as you expect a int or a float, you can set up type=float in add_argument as int is a subset of float. Or you can just remove the type parameter to accept whatever type you pass to it.
thanks ! Was wondering as to why you removed the old answer (one using sys.argv)- you can keep the old answer alongside with the new answer so that it can be helpful for others who visit this post. :) have upvoted your answer and marked your solution as accepted :)
I removed it as I wanted to answer your question very accurately, bespoke to your need. Indeed the first version was working as well, I just edited the answer, now both solutions are available.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.