简体   繁体   中英

dataframe fill empty column values based on values with same index (using PANDAS)

I have the following dataframe where the index is the tag# . I want to fill all of the NaN values in the sound column with the correct values based on matching indexes.

        pet    sound
tag#        
11      cat 
11      cat    meow
11      cat    meow
15      bird   tweet
8       pig    oink
5       dog 
8       pig 
8       pig 
8       pig 
5       dog    woof
5       dog    woof
11      cat    meow

I want the dataframe to look like this

        pet    sound
tag#        
11      cat    meow
11      cat    meow
11      cat    meow
15      bird   tweet
8       pig    oink
5       dog    woof
8       pig    oink 
8       pig    oink 
8       pig    oink 
5       dog    woof
5       dog    woof
11      cat    meow

Try with groupby apply on level 0 and ffill + bfill each group:

df = df.groupby(level=0).apply(lambda g: g.ffill().bfill())
       pet  sound
tag#             
11     cat   meow
11     cat   meow
11     cat   meow
11     cat   meow
15    bird  tweet
8      pig   oink
8      pig   oink
8      pig   oink
8      pig   oink
5      dog   woof
5      dog   woof
5      dog   woof

Complete Working Example:

import pandas as pd
from numpy import nan

# Re-create DataFrame
df = pd.DataFrame({
    'tag#': [11, 11, 11, 15, 8, 5, 8, 8, 8, 5, 5, 11],
    'pet': ['cat', 'cat', 'cat', 'bird', 'pig', 'dog', 'pig',
            'pig', 'pig', 'dog', 'dog', 'cat'],
    'sound': [nan, 'meow', 'meow', 'tweet', 'oink', nan, nan,
              nan, nan, 'woof', 'woof', 'meow']
}).set_index('tag#')

df = df.groupby(level=0).apply(lambda g: g.ffill().bfill())
print(df)

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