294-2 camelCase to snake_case

Hello I’m working on project ‘Exploring Ebay Car Sales Data’ where I’m asked to convert camelCase to snake_case. I tried and did a bit of research but haven’t found a good/concise solution yet. Could someone help suggest? Thank you.

Hey there @spxzhang, welcome to the community!

For the purpose of this project, you can simply copy the list of column names, then edit each one. That’s the method outlined in the solutions.

So you do the following:

autos.columns

Output:

Index(['dateCrawled', 'name', 'seller', 'offerType', 'price', 'abtest',
       'vehicleType', 'yearOfRegistration', 'gearbox', 'powerPS', 'model',
       'odometer', 'monthOfRegistration', 'fuelType', 'brand',
       'notRepairedDamage', 'dateCreated', 'nrOfPictures', 'postalCode',
       'lastSeen'],
      dtype='object')

Then, you copy the list above, make your edits manually, and simply reassign them as column names like so:

autos.columns = ['date_crawled', 'name', 'seller', 'offer_type', 'price', 'ab_test',
       'vehicle_type', 'registration_year', 'gearbox', 'power_ps', 'model',
       'odometer', 'registration_month', 'fuel_type', 'brand',
       'unrepaired_damage', 'ad_created', 'num_photos', 'postal_code',
       'last_seen']

There’s also a number of other ways to do it using tools like regex or the inflection library. Check out this topic on StackOverflow. It boils down to finding Upper-case letters that aren’t the first, inserting underscores before them, and then lower-casing the entire string.

1 Like

Hint: Find uppercase characters and replace them with their lowercase counterpart preceded by an underscore.

2 Likes

Hey , i used autos.columns.str.lower() to change all the column names to lowercase , then used autos.rename() to change the rest of the column names to snake _case.

I hope this is helpful