replacing empty strings with NaN in Pandas

前端 未结 2 2022
天涯浪人
天涯浪人 2020-12-30 05:26

I have a pandas dataframe (that was created by importing a csv file). I want to replace blank values with NaN. Some of these blank values are empty and some contain a (varia

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 06:06

    If you are reading a csv file and want to convert all empty strings to nan while reading the file itself then you can use the option

    skipinitialspace=True
    

    Example code

    pd.read_csv('Sample.csv', skipinitialspace=True)
    

    This will remove any white spaces that appear after the delimiters, Thus making all the empty strings as nan

    From the documentation http://pandas.pydata.org/pandas-docs/stable/io.html

    Note: This option will remove preceding white spaces even from valid data, if for any reason you want to retain the preceding white space then this option is not a good choice.

提交回复
热议问题