[英]Replace NaN values in pandas dataframe with a computation from other columns
I have a DataFrame with column3 containing NaN values.我有一个 DataFrame ,其 column3 包含 NaN 值。 I want to replace these NaN values with column2-column1.我想用 column2-column1 替换这些 NaN 值。 But column 2 is a string and I want to take the first four digits from the string and convert it to integer before subracting.但是第 2 列是一个字符串,我想从字符串中取出前四位数字并将其转换为 integer 在减法之前。
I tried this:我试过这个:
df.column3.fillna(int(df.column2[:4]) - df.column1)
And I get this following error:我收到以下错误:
TypeError: cannot convert the series to <class 'int'> TypeError:无法将系列转换为 <class 'int'>
Use str[:4]
for first 4 values of strings with convert to numeric by Series.astype
:将str[:4]
用于字符串的前 4 个值,并通过Series.astype
转换为数字:
df.column3 = df.column3.fillna(df.column2.str[:4].astype(int) - df.column1)
Or by to_numeric
if first solution failed:或者如果第一个解决方案失败,则通过to_numeric
:
df.column3 = df.column3.fillna(pd.to_numeric(df.column2.str[:4], errors='coerce') - df.column1)
Use:利用:
df.column3.fillna(df.column2.str[:4].astype('int') - df.column1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.