pandas 数据类型转换

pandas还有 pd.to_numeric(arg,errors='raise')pd.to_datetime(arg,errors='raise') 函数帮助我们转为数据类型。
errors参数有:

  • raise, errors默认为raise
  • ignore 忽略错误
  • coerce 将错误数据标注为NaN
    1. pd.to_numeric(df['Jan Units'], errors='coerce')
    2. """
    3. 0
    4. 500.01
    5. 700.02
    6. 125.03
    7. 75.04
    8. NaNName: Jan Units, dtype: float64
    9. """
    将处理结果中的NaN用0替代
    1. df['Jan Units'] = pd.to_numeric(df['Jan Units'], errors='coerce').fillna(0)df['Jan Units']
    2. """
    3. 0
    4. 500.01
    5. 700.02
    6. 125.03
    7. 75.04
    8. 0.0
    9. Name: Jan Units, dtype: float64
    10. """
    在进行数据类型转换的时候,比如一列是浮点数的含有缺失值,如果要转为int整数类型,直接转换会报错,这个时候,想要填充缺失值,再进行转换
    1. df['金牌数'] = df['金牌数'].fillna('0').astype(int)
    或者
    1. df['金牌数'].replace(np.nan,0,inplace=True)
    2. df['金牌数'] = [int(i) for i in df['金牌数']]
    当对None进行替换的时候,用"None"而不是直接None

两个时间相减会返回一个timedelta类型的数据,用来表示时间间隔

  1. data['住院天数'] = data['出院时间']-data['入院时间']
  2. data['住院天数'] = data['住院时间'].apply(lambda x: x.days)
  • timedelta数据是一个对象,有相应的属性,timedelta.days可以返回间隔天数