pandas 数据类型转换
pandas还有 pd.to_numeric(arg,errors='raise')
和pd.to_datetime(arg,errors='raise')
函数帮助我们转为数据类型。
errors参数有:
- raise, errors默认为raise
- ignore 忽略错误
- coerce 将错误数据标注为NaN
将处理结果中的NaN用0替代pd.to_numeric(df['Jan Units'], errors='coerce')
"""
0
500.01
700.02
125.03
75.04
NaNName: Jan Units, dtype: float64
"""
在进行数据类型转换的时候,比如一列是浮点数的含有缺失值,如果要转为int整数类型,直接转换会报错,这个时候,想要填充缺失值,再进行转换df['Jan Units'] = pd.to_numeric(df['Jan Units'], errors='coerce').fillna(0)df['Jan Units']
"""
0
500.01
700.02
125.03
75.04
0.0
Name: Jan Units, dtype: float64
"""
或者df['金牌数'] = df['金牌数'].fillna('0').astype(int)
当对None进行替换的时候,用df['金牌数'].replace(np.nan,0,inplace=True)
df['金牌数'] = [int(i) for i in df['金牌数']]
"None"
而不是直接None
两个时间相减会返回一个timedelta类型的数据,用来表示时间间隔
data['住院天数'] = data['出院时间']-data['入院时间']
data['住院天数'] = data['住院时间'].apply(lambda x: x.days)
- timedelta数据是一个对象,有相应的属性,
timedelta.days
可以返回间隔天数