
[英]How to replace NaN value in one column based on the value of another column in the same row using Pandas?
[英]Using Python Pandas, can I replace values of one column in a df based on another column only when a "nan" value does not exist?
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
假设我有一个这样的数据框:
import pandas as pd
data1 = {
"date": [1, 2, 3],
"height": [420.3242, 380.1, 390],
"height_new": [300, 380.1, "nan"],
"duration": [50, 40, 45],
"feeling" : ["great","good","great"]
}
df = pd.DataFrame(data1)
我想用“height_new”列更新“height”列,但不是在“height_new”的值为“nan”时更新。 关于如何以 Pythonic 方式执行此操作的任何提示?
我有一个粗略的代码可以完成工作但感觉很笨拙(代码行太多)。
for x, y in zip(df['height'], df['height_new']) :
if y != 'nan':
df['height'].replace(x, y, inplace= True)
x = y
您可以将pandas.Series.where
与pandas.Series.notna
一起使用:
df["height"] = df["height_new"].where(df["height_new"].notna(), df["height"])
print(df)
date height height_new duration feeling
0 1 300.0 300.0 50 great
1 2 380.1 380.1 40 good
2 3 390.0 NaN 45 great
注意:如果"nan"
是文字字符串,请改用它:
df["height"] = df["height_new"].where(df["height_new"].ne("nan"), df["height"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.