Replacing each Null value in dataframe with a list

前端 未结 2 1025
名媛妹妹
名媛妹妹 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:42

    Are you looking for this:

    In [4422]: df[df.columns[df.isna().any()]] = CB
    
    In [4423]: df
    Out[4423]: 
       a    b    c    d
    0  0  1.0  2.0  3.0
    

    EDIT:

    Consider below df:

    In [4621]: df
    Out[4621]: 
       a    b    c    d
    0  0  4.0  5.0  6.0
    1  0  NaN  NaN  NaN
    2  0  NaN  NaN  NaN
    

    If you want to change NaN values in only last row, do this:

    Get the column names which have NaN in last row:

    In [4623]: cols = df.columns[df.iloc[-1].isna()]
    In [4631]: cols
    Out[4631]: Index(['b', 'c', 'd'], dtype='object')
    

    Now, set the values for these cols from list CB:

    In [4631]: CB = [1, 2, 3]
    
    In [4628]: df.loc[df.index[-1], cols] = CB
    
    In [4629]: df
    Out[4629]: 
       a    b    c    d
    0  0  4.0  5.0  6.0
    1  0  NaN  NaN  NaN
    2  0  1.0  2.0  3.0
    

提交回复
热议问题