Is it possible to force pandas not to convert data type when using DataFrame.replace

ayhan 08/21/2017. 2 answers, 200 views
python pandas

Here's a working example:

df = pd.DataFrame({'A': [-39882300000000000000]}, dtype='object')

df.replace({',': '.'}) raises an OverflowError because somewhere in the code the convert flag is set to True. I am not sure but it is probably because pandas is inferring that it only contain numbers.

I read the data from an Excel workbook and I want to prevent this conversion when using df.replace. Is there a way to do so?

1 Comments
1 piRSquared 08/21/2017
IIUC convert it to str. df.astype(str).replace({',': '.'})

2 Answers


piRSquared 08/21/2017.
df.update(df.blocks['object'].astype(str).replace({',': '.'}))
5 comments
1 MaxU 08/21/2017
df.blocks['object'] - wow! This is cool!
1 piRSquared 08/21/2017
You remember I brought it up a while ago... this is the first time I've used it to answer a question (-:
1 MaxU 08/21/2017
@ayhan, there is a documented method: pandas.pydata.org/pandas-docs/stable/generated/…
1 piRSquared 08/21/2017
@ayhan neither does get_value or set_value but jeff told me that it wasn't intended as public api. So, still not sure
1 piRSquared 08/22/2017
@Jeff what specifically? blocks, as_blocks, or get/set_value?

MaxU 08/21/2017.

How about this:

In [25]: df.loc[:, df.dtypes=='object'] = \
             df.select_dtypes(['object']).astype(str).replace({',': '.'})

This will apply .replace only to columns of a string (object) dtype

Related questions

Hot questions

Language

Popular Tags