简体   繁体   中英

Need help filling in blanks on a pandas Dataframe

I have a dataframe that contains Names and associated numbers. The issue is that the values don't associate with the Names. Here is an example below:

在此处输入图像描述

All the values should be associated with the name that starts before the values start appearing. The result should look something like this:

在此处输入图像描述

I am struggling to come up with the logic that would get this done and any help would be appreciated. I can figure out how to remove the blank values on my own shown in the second example.

Thanks!

import pandas as pd
import numpy as np

If your 'Name' column don't contains NaN's(it contains '' or ' ' ) then make use of replace() method(If it contains NaN's then Ignore this step):

df['Name']=df['Name'].replace('',np.nan,regex=True)
df['Name']=df['Name'].replace(' ',np.nan,regex=True)

Just use ffill() method:

df['Name']=df['Name'].ffill()

OR

you can also do this by fillna() method:

df['Name']=df['Name'].fillna(method='ffill')

Now if you print df you will get your desired output

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