简体   繁体   English

如何根据另一列中的值有条件地替换一列中的 NaN 值

[英]How to conditionally replace NaN values in a column based on values in another column

Say I have a dataframe with the following values:假设我有一个具有以下值的 dataframe:

Course_Code科目编号 Department部门
CS201 CS201 CompSci计算机科学
CS202 CS202 NaN钠盐

I would appreciate if someone could help me how to replace the NaN values in the "Department" column based on the values in the column "Course Code".如果有人可以帮助我如何根据“课程代码”列中的值替换“部门”列中的 NaN 值,我将不胜感激。 The logic to follow is to replace the NaN as "CompSci" if "CS" is in the "Course Code" entry for that row.要遵循的逻辑是,如果“CS”在该行的“课程代码”条目中,则将 NaN 替换为“CompSci”。

You could create a mapping that you could use to fill in NaN values.您可以创建一个可用于填充 NaN 值的映射。 One option to create the mapping is to use mask to select values where Course_Code starts with "CompSci":创建映射的一个选项是使用mask到 select 值,其中Course_Code以“CompSci”开头:

df['Department'] = df['Department'].mask((df['Course_Code'].str.startswith('CS')) & df['Department'].isna(), 'CompSci')

Output: Output:

  Course_Code Department
0       CS201    CompSci
1       CS202    CompSci

You could use more condition as 'CS' for CompSci.您可以使用更多条件作为 CompSci 的“CS”。

import pandas as pd 
import numpy as np
df = pd.DataFrame([['CS201', 'CompSci'],['CS201', np.NaN]], columns = ['Course_Code', 'Department'])

def condition(x):
    if (x['Course_Code'].startswith('CS')):
        return "CompSci"

df['Department'] = df.apply(condition, axis=1)

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

相关问题 Pandas:如何根据另一列替换列中的 Nan 值? - Pandas: How to replace values of Nan in column based on another column? 如果另一列是NaN,如何替换列中的值? - How to replace values in a column if another column is a NaN? 如何基于其他列的某些值替换列的nan值 - How to replace nan values of a column based on certain values of other column 如何根据另一列的值替换列的NaN值? - How to substitute NaN values of a column based on the values of another column? 如何根据另一列中的值用另一列的平均值替换 NaN 值? Pandas - How to replace NaN values with another column's mean based on value in another column? Pandas 如何根据同一 dataframe 中另一列的值替换 Dataframe 中列中的 NaN 值 - How to replace NaN value in column in Dataframe based on values from another column in same dataframe 如何根据另一列的条件替换一列的NaN值? - How to replace NaN values from a column based on a condition from another column? 有条件地根据另一列中的值替换值 - Conditionally replacing values based on values in another column 如何根据另一列中的单元格值有条件地填充 Pandas 列 - How to Conditionally Fill Pandas Column based on Cell Values in another column 如何基于另一列的NaN值设置熊猫数据框中的值? - How set values in pandas dataframe based on NaN values of another column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM