Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace blank space with "_" on every element's list - Python

I imported a .csv file with this command:

 mydata = pd.read_csv(file ,sep='\t' , engine='python' , dtype = {'Day' : np.datetime64 , 'Year' : np.int}  )

But i noticed than some of the column name has blank spaces like Account id instead of Account_id

Now i got the list of my columns name with this:

dwb_col= data.columns

And i'd like to replace blank spaces " " with "_" sign on every column name (i.e. every dwb_col element).

in order to rename the columns in this way: mydata.columns = [my_new_columns_list]

  1. How i can do the find and replace part?

  2. Is there any workaround/shortcut during the importing fase that let me collect the column name with "_"(underscore sign) over the " " (space) ?

like image 470
pellerossa pelles Avatar asked Dec 04 '19 13:12

pellerossa pelles


1 Answers

This will do, using str.replace:

df.columns = df.columns.str.replace(" ", "_")
like image 123
prp Avatar answered Oct 05 '22 21:10

prp