How to read the dataset (.data and .names) directly into Python DataFrame from UCI Machine Learning Repository

Viewed 5185

I am looking a way to read the dataset directly from UCI Machine Learning repository. But i am only able to get dataset.. not its description.

Here is the link https://archive.ics.uci.edu/ml/datasets/Car+Evaluation and https://archive.ics.uci.edu/ml/machine-learning-databases/car/ to the data I want to import.

The files are .data and .names. How do you import them into Python as a data frame? I have tried as below.. where i have to manually write the features or column names. Is there a way we can read .names file and set the features from there. Creating the feature names manually might be ok for dataset with handful of features.. but as features grow it will be hard to do it manually.

# Without Column Names
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/car/car.data', header=None)

# Generating Column Name manually.
names=[ 'buying','maint','doors','persons','lug_boot','safety','class']
df2 = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/car/car.data', names = names)

Any help, will be appreciated. Thanks.

1 Answers

.names files are unstructered, unfortunately for this reason you would have to open the file and extract the column names manually. Once you do so, you could add these names into a list. Given that you have multiple .data files and that these are in the same order, you could use a for loop to label the column names and read the datafiles simultaneously.

    column_names = ["example1", "example2", "example3"]
    data_list =[]
    data = ["link to the sourcefile/file.data", "link to the 
             sourcefile/file.data", "link to the sourcefile/file.data"]

    for file in data:
        df = pd.read_csv(file, names = column_names)
        data_list.append(df) 
Related