我有一个DataFrame,其中column3包含NaN值。我想将这些NaN值替换为column2-column1。但是第2列是一个字符串,我想从字符串中获取前四位数字,然后将其转换为整数,然后再进行减法运算。
我尝试了这个:
df.column3.fillna(int(df.column2[:4]) - df.column1)
我得到以下错误:
TypeError:无法将系列转换为<class'int'>
使用str[:4]
与转换为数值的字符串的第4个值Series.astype
:
df.column3 = df.column3.fillna(df.column2.str[:4].astype(int) - df.column1)
或者,to_numeric
如果第一个解决方案失败:
df.column3 = df.column3.fillna(pd.to_numeric(df.column2.str[:4], errors='coerce') - df.column1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句