Home > database >  How to write these functions in smaller amount of code?
How to write these functions in smaller amount of code?

Time:12-21

I have a long list of car developers and relevant data which I need to import into Python, and have to create a new column called "manufacturer" corresponding to each manufacturer. How can I do this more concicely

import zipfile

zf = zipfile.ZipFile(r"C:\Users\aksel\Downloads\Cars.zip") 

zf.namelist() 
 
audi = pd.read_csv(zf.open("Audi.csv"))
bmw = pd.read_csv(zf.open("BMW.csv"))
ford = pd.read_csv(zf.open("Ford.csv"))

audi["manufacturer"] = "audi"
bmw["manufacturer"] = "bmw"
ford["manufacturer"] = "ford"


cars = pd.concat([audi, bmw, ford, hyundai, mercedes, skoda, toyota, vw])

CodePudding user response:

Don't use separate variables, use a list and a loop.

cars_list = []
for filename in zf.namelist():
    car = pd.read_csv(zf.open(filename))
    car["manufacturer"] = filename.replace(".csv", "").lower()
    cars_list.append(car)

cars = pd.concat(cars_list)
  • Related