简体   繁体   中英

Is there a way to overwrite Nan values in a pandas dataframe with values of the previous row?

I am working with a dataframe called ´tabla_combinada´ that looks like this:

Structure of the dataframe used:

在此处输入图像描述

What I am attempting to do is to get rid of the Nan values in the 'End Meter' column and replace it with the value of the same column in the previous row. I tried to implement the following code:

counter=0
for x in tabla_combinada['End Meter']:
    if math.isnan(x):
        x = tabla_combinada['End Meter'][counter-1]
        tabla_combinada['End Meter'][counter-1] = tabla_combinada['Start Meter'][counter]       
    counter = counter + 1

This is not working for me, in the first place I am getting the following warning:

A value is trying to be set on a copy of a slice from a DataFrame.

But what bugs me is that I am obtaining no change in the dataframe at all. I do understand the cause of the warning and I suspect that this is not the optimal approach to solve the problem. I guess there is a proper way to do this with loc, but I couldn't find out how to tell the program to replace the Nan with the value of the previous row. Sorry for the long question and thanks in advance.

All you need to do is this:

tabla_combinada['End Meter'].fillna(method='ffill')

This will propagate non-null values forward

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM