Replacing each Null value in dataframe with a list

前端 未结 2 1051
名媛妹妹
名媛妹妹 2021-01-26 03:53

I am trying to replace each instance of null value by a different value each time. The values are in a list CB.

import pandas as pd
import numpy as np
df = pd.Dat         


        
2条回答
  •  难免孤独
    2021-01-26 04:36

    Let's say we have a dataframe (making it a bit bigger that the original question)

    df = pd.read_csv(StringIO(
    """
       a   b   c   d
    0  0   4   5   6
    1  0 NaN NaN NaN
    """), delim_whitespace=True)
    

    then we can do the following

    dfs = df.stack(dropna = False)
    dfs[dfs.isna()] = CB
    df = dfs.unstack()
    df
    

    produces

        a   b   c   d
    0   0.0 4.0 5.0 6.0
    1   0.0 1.0 2.0 3.0
    

    Here we unwrap the df into a timeseries using stack(), filter to NaNs, replace with CB, and fold back into the original shape

提交回复
热议问题