I'm reading a csv file using pandas.read_csv(). My csv file has headers with spaces at start or end like ' header1', 'header2 ' I want to trim that extra space at start/end. Is their a way to specify this using some arguments? If not how to achieve that in my resultant dataframe?
            Asked
            
        
        
            Active
            
        
            Viewed 1,634 times
        
    3
            
            
         
    
    
        DevLoverUmar
        
- 11,809
- 11
- 68
- 98
- 
                    1You could try `df.columns =[col.strip() for col in df.columns]` after reading the csv. – MrNobody33 Jul 11 '20 at 10:41
1 Answers
3
            You could try with this, after reading the csv:
df.columns =[col.strip() for col in df.columns]
Same as:
df.rename(columns=lambda x: x.strip(), inplace=True)
Or this too:
df.columns=df.columns.str.strip()
 
    
    
        MrNobody33
        
- 6,413
- 7
- 19
- 
                    
- 
                    1@MuhammadUmarFarooq I think the last one is the msot clear and idiomatic method. Good answer. – Umar.H Jul 11 '20 at 10:52
- 
                    2I agree with Datanovice, I would use the last one @MuhammadUmarFarooq. Also, the list comprehension it's a good option and in most cases it could be the fastest way. – MrNobody33 Jul 11 '20 at 10:57
- 
                    1i would steer clear from method two, using `inplace=True` offers no real benefit and from what i remember may be depreicated in future pandas versions. – Umar.H Jul 11 '20 at 11:10
- 
                    1
- 
                    1@MuhammadUmarFarooq actually, I just find another possible solution to your problem, they used regex for the separator; like `sep="\s*,\s*"`, but as you can see in the comments(of the answer), it could yield problems. Here is the answer: [link](https://stackoverflow.com/a/55806282/13676202) – MrNobody33 Jul 11 '20 at 11:19
- 
                    1
- 
                    BTW @MuhammadUmarFarooq, if you find the answer helpful, you may consider accepting it :) – MrNobody33 Jul 11 '20 at 12:05
- 
                    1Of course I'll accept. But give me some time, if anyone else want to answer my question. – DevLoverUmar Jul 11 '20 at 12:07
-