Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas.DataFrame.str.replace function replaces floats to NaN

I have a Pandas DataFrame, suppose: df = pd.DataFrame({'Column name':['0,5',600,700]})

I need to remove ,. The code is: df_mod = df.stack().str.replace(',','').unstack()

As a result I get: [05, NaN, NaN]

Do you have any ideas why my expression replaces numbers with NaN and how to avoid it? Thanks a lot!

like image 746
Vlad Avatar asked Apr 03 '17 14:04

Vlad


People also ask

How do I replace missing values with NaN?

You can replace the missing value ( NaN ) in pandas. DataFrame and Series with any value using the fillna() method.

How do you replace values in a DataFrame based on a condition?

You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.

How do you replace all NaN values with string in pandas?

We can replace the NaN with an empty string using df. replace() function. This function will replace an empty string inplace of the NaN value.


1 Answers

Those numbers are treated as numeric values, which don't have str.replace methods, you can convert the column to string, remove the comma, and then convert the data type back:

df['Column name'].astype(str).str.replace(",", "").astype(int)

#0      5
#1    600
#2    700
#Name: Column name, dtype: int64
like image 176
Psidom Avatar answered Oct 11 '22 12:10

Psidom