0

I get 'TypeError: data type not understood' when trying to execute a line of code that looks like this:

df['c'].replace(0, method='ffill', inplace=True)

The code above is basically to replace every zero value with its previous non-zero value in column c. The data type of values in column c is integer with only two NaNs. The error still occurs after replacing the NaNs with zeros, but it works fine when I add the following line before the above code:

df.dropna(inplace = True)

So what does actually happen here? How can I replace every zero value with its previous non-zero value in column c without deleting any row with NaNs in my DataFrame?

1 Answers1

2

Assuming all the missing data are handled i.e. NaNs replaced with some desired value,

some_desired_value = 0 # Maybe different in your case
df['c'] = df['c'].fillna(some_desired_value)

Replace zeros with NaN and then forward-fill

df['c'].replace(0, pd.np.nan).ffill()

Even your code should work if there are no undesired value in column

df['c'].replace(0, method='ffill', inplace=True)
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55