简体   繁体   English

使用 Python Pandas,仅当“nan”值不存在时,我可以根据另一列替换 df 中一列的值吗?

[英]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?

Let's say I have a data frame like this:假设我有一个这样的数据框:

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)

And I want to update the "height" column with the "height_new" column but not when the value for "height_new" is "nan".我想用“height_new”列更新“height”列,但不是在“height_new”的值为“nan”时更新。 Any hints on how to do this in a Pythonic manner?关于如何以 Pythonic 方式执行此操作的任何提示?

I have a rough code which gets the job done but feels clunky (too many lines of code).我有一个粗略的代码可以完成工作但感觉很笨拙(代码行太多)。

for x, y in zip(df['height'], df['height_new']) :
  if y != 'nan':
    df['height'].replace(x, y, inplace= True)
    x = y

You can use pandas.Series.where with pandas.Series.notna :您可以将pandas.Series.wherepandas.Series.notna一起使用:

df["height"] = df["height_new"].where(df["height_new"].notna(), df["height"])

# Output: #Output:

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

NB: If "nan" is a literal string, use this instead:注意:如果"nan"是文字字符串,请改用它:

df["height"] = df["height_new"].where(df["height_new"].ne("nan"), df["height"])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Pandas 根据同一行中另一列的值替换一列中的 NaN 值? - How to replace NaN value in one column based on the value of another column in the same row using Pandas? 基于另一个 DF 替换 pandas 列值 - Replace pandas column values based on another DF Python pandas 用模式(同一列 -A)相对于 Pandas 数据帧中的另一列替换一列(A)的 NaN 值 - Python pandas replace NaN values of one column(A) by mode (of same column -A) with respect to another column in pandas dataframe Pandas:如何根据另一列替换列中的 Nan 值? - Pandas: How to replace values of Nan in column based on another column? 如何根据另一列中的值用另一列的平均值替换 NaN 值? Pandas - How to replace NaN values with another column's mean based on value in another column? Pandas Python Pandas 将一列中的 NaN 替换为与列表列相同行的另一列中的值 - Python Pandas replace NaN in one column with value from another column of the same row it has be as list column 基于另一列中的值替换pandas df中的值 - Replace values in a pandas df based off values in another column 根据另一个df python pandas更新df列值 - update df column value based on another df python pandas 基于另一列的值对一列Pandas DF进行条件运算 - Conditional operation on one column of Pandas DF based on value of another column 根据另一列中的值,用字符串替换一列中的NaN - Replace NaN's in one column with string, based on value in another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM