Formatting column names with pandas

For a task, I needed to do was to add speech marks around values in a CSV file. for example “http://example.com/", “0” . When finished the task it only took around 20 lines of code. But taking lots of googling around to complete this simple task. The first solution I thought of was to add two speech mark string at the beginning and end of the columns. like this, df["url"] = ”’” + df.loc[:,["url"]] + "'"

It was able to work for one of the columns. I wasn’t sure why it did not work for the second column, As I printed the column as normal it successfully worked. First, I found out that the name of the second column had whitespace when checking the CSV file. I printed the column names as a list using this command: list(my_data.columns.values)to see the error in pandas and making and before and after. When making a variable for the pandas series after striping the column.

After the prompt stating printing an error that said it can’t concatenate strings with an int, I quickly learned that the second column needed to be a string. Even though the second column mainly contained numbers I just assumed it will be a string. After I added this function df["score"] = df["score"].apply(str)to change the series into a string data type next. after I tried concatenating the speech marks strings together with the pandas series, this time it worked.

Next, the pandas series need to be stitched together. To do this you can use the conat() function and maybe print df.head()or df.tail()to preview the dataframe. Now the dataframe is ready to export so next use the to_csv()function. Something I found out when doing this, Is when to CSV file was made pandas gave the values extra quotes, for example, the values in the CSV looked like this

“””www.example.com""" “””0"””

To fix this you have to import the CSV module and set quoting = csv.QUOTE_NONE in the to_csv() function.

$\setCounter{0}$
Previous
Previous

What AI can learn from AI in video games?

Next
Next

Web Scraping laptops prices with BeautifulSoup