Convert Pandas series containing string to boolean

前端 未结 4 1117
慢半拍i
慢半拍i 2020-12-01 07:58

I have a DataFrame named df as

  Order Number       Status
1         1668  Undelivered
2        19771  Undelivered
3    100032108  Undelivered
4         


        
4条回答
  •  孤独总比滥情好
    2020-12-01 08:21

    Expanding on the previous answers:

    Map method explained:

    • Pandas will lookup each row's value in the corresponding d dictionary, replacing any found keys with values from d.
    • Values without keys in d will be set as NaN. This can be corrected with fillna() methods.
    • Does not work on multiple columns, since pandas operates through serialization of pd.Series here.
    • Documentation: pd.Series.map
    d = {'Delivered': True, 'Undelivered': False}
    df["Status"].map(d)
    

    Replace method explained:

    • Pandas will lookup each row's value in the corresponding d dictionary, and attempt to replace any found keys with values from d.
    • Values without keys in d will be be retained.
    • Works with single and multiple columns (pd.Series or pd.DataFrame objects).
    • Documentation: pd.DataFrame.replace
    d = {'Delivered': True, 'Undelivered': False}
    df["Status"].replace(d)
    

    Overall, the replace method is more robust and allows finer control over how data is mapped + how to handle missing or nan values.

提交回复
热议问题