How to replace 'any strings' with nan in pandas DataFrame using a boolean mask?

前端 未结 3 1340
自闭症患者
自闭症患者 2020-12-30 06:48

I have a 227x4 DataFrame with country names and numerical values to clean (wrangle ?).

Here\'s an abstraction of the DataFrame:

import pandas as pd
i         


        
3条回答
  •  无人及你
    2020-12-30 07:19

    cols = ['Measure1','Measure2']
    df[cols] = df[cols].applymap(lambda x: x if not isinstance(x, str) else np.nan)
    

    or

    df[cols] = df[cols].applymap(lambda x: np.nan if isinstance(x, str) else x)
    

    Result:

    In [22]: df
    Out[22]:
      Country Name  Measure1  Measure2
    0          nBl      10.0       9.0
    1          Ayp       8.0       NaN
    2          diz       4.0       1.0
    3          aad       7.0       3.0
    4          JYI       NaN      10.0
    5          BJO       9.0       8.0
    

提交回复
热议问题