pppp
pppp

Reputation: 677

Replace all commas with an empty space in csv error

I'm trying to replace all the commas with an empty space in a single column in a csv. I tried the following method here:

df["column_name"].replace(",", " ")

However I got the following error:

replace(self, to_replace, value, inplace, limit, regex, method, axis)
   3108                 elif not com.is_list_like(value):  # NA -> 0
   3109                     new_data = self._data.replace(to_replace=to_replace, value=value,
-> 3110                                                   inplace=inplace, regex=regex)
   3111                 else:
   3112                     msg = ('Invalid "to_replace" type: '    

replace(self, **kwargs)
   2868 
   2869     def replace(self, **kwargs):
-> 2870         return self.apply('replace', **kwargs)
   2871 
   2872     def replace_list(self, src_list, dest_list, inplace=False, regex=False, mgr=None):

apply(self, f, axes, filter, do_integrity_check, consolidate, **kwargs)
   2821 
   2822             kwargs['mgr'] = self
-> 2823             applied = getattr(b, f)(**kwargs)
   2824             result_blocks = _extend_blocks(applied, result_blocks)
   2825 

replace(self, to_replace, value, inplace, filter, regex, convert, mgr)
        605 
        606             # we can't process the value, but nothing to do
    --> 607             if not mask.any():
        608                 return self if inplace else self.copy()
        609 

    UnboundLocalError: local variable 'mask' referenced before assignment

I did a bit of research on the nature of this error message but I can't figure out where I would be referencing a variable before assignment.

Upvotes: 3

Views: 3256

Answers (2)

Saihaj
Saihaj

Reputation: 516

You might have to set Regex flag to True

 df["column_name"].replace(",", " ", regex=True)

Upvotes: 0

Mike Müller
Mike Müller

Reputation: 85442

Assuming df["column_name"] is of type string, this should work:

df["column_name"].str.replace(","," ")

You can assign the result to the column:

df["column_name"] = df["column_name"].str.replace(","," ")

Upvotes: 1

Related Questions