【问题标题】:How to fill a nan value in a column with value of column which has same values for other columns如何用与其他列具有相同值的列的值填充列中的 nan 值
【发布时间】:2021-09-02 00:31:02
【问题描述】:

这是毕马威虚拟实习的问题

我的问题是如何用具有相同职位的列的 job_industry 值填充 nan values job_industry 列

例如:

job_title               job_industry

Quality Engineer        Financial Services
Quality Engineer        Nan

我希望将 job_industry 的 nan 值填充为 Financial Services

如果 job_industry 中存在一个 nan 值,而 job_title 是 General manager,则用 Manufacturing 填充它

【问题讨论】:

  • 欢迎您!请提供一个最小且可执行的示例。如需更多信息,请参阅here

标签: python pandas


【解决方案1】:

使用groupby.ffillgroupby.bfill 自动填充每个job_title 缺少的job_industry

g = df.groupby('job_title')['job_industry']
df['job_industry'] = g.ffill()
df['job_industry'] = g.bfill()

#           job_title        job_industry
# 0  Quality Engineer  Financial Services
# 1  Quality Engineer  Financial Services

请注意,从技术上讲,简化的 2 行示例不需要bfill,但实际数据需要。

【讨论】:

  • @Rinshan 我想为您的代码提供类似的输出,但在某些空间仍然有 NaN 值
  • 用我的代码还是 Rinshan 的代码? Rinshan 的回答有一些我在 cmets 中描述的问题。我的代码不应该产生任何 NaN,除非有一个 job_title 具有 all NaN 用于 job_industry(在这种情况下,不可能知道 job_industryjob_title)跨度>
  • 请用我放的数据框测试,输出有问题
  • 好的,感谢您告诉我有关 ffill 和 bfill 的信息
【解决方案2】:

我将首先在job_industryjob_title 之间创建一个映射(Python 字典),然后将job_industry 列的映射分配给job_title 的NaN 值。

代码如下:

df = pd.DataFrame(
    columns=["job_title", "job_industry"],
    data=[["Quality Engineer", "Financial Services"], ["Quality Engineer", None]]
)

# May be there is a faster way
title_industry_mapping = df.dropna(["job_industry"]).set_index("job_title")["job_industry"].drop_duplicates().to_dict()

isna = df["job_industry"].isna()
df.loc[isna, "job_industry"] = df.loc[isna, "job_title"].replace(title_industry_mapping)

结果:

job_title job_industry
0 Quality Engineer Financial Services
1 Quality Engineer Financial Services

【讨论】:

    【解决方案3】:
    import pandas as pd
    import numpy as np
    df = pd.DataFrame([
         ['Quality Engineer','Financial Services'],
         ['Progammer',np.nan],
         ['Quality Engineer',np.nan],
         ['Progammer',"IT"],
         ['General manager',np.nan]],
        columns=['job_title','job_industry'])
    with pd.option_context('mode.use_inf_as_null', True):
        df = df.sort_values('job_industry', ascending=False, na_position='last')
    df["job_industry"].loc[(df['job_title'] == "General manager") & (df['job_industry'].isnull())] = "Manufacturing"
    df['job_industry'] = df.groupby('job_title')['job_industry'].fillna(method="ffill")
    

    df['job_industry'].isnull(),这将验证job_industry 列是否为空。

    下面的代码会按照job_industry列的null值降序排序,因为如果nan值出现在前面,nan的初始值不会被替换。

    with pd.option_context('mode.use_inf_as_null', True):
        df = df.sort_values('job_industry', ascending=False, na_position='last')
    

    如果你更喜欢排序而不是输出,你可以试试,df.sort_index()

    O/P

    +----+------------------+-------------------------------------------------------+
    |    | job_title        | job_industry                                          |
    |----+------------------+-------------------------------------------------------|
    |  0 | Quality Engineer | Financial Services                                    |
    |  1 | Progammer        | IT                                                    |
    |  2 | Quality Engineer | Financial Services                                    |
    |  3 | Progammer        | IT                                                    |
    |  4 | General manager  | Manufacturing                                         |
    +----+------------------+-------------------------------------------------------+
    

    【讨论】:

    • 方法 1 填补了所有个金融服务职位。如果位置的第一个 job_industry 为空,方法 2 将无法正常工作。方法3只是从我的答案中复制的。
    • 是的,当然,你的答案是完美的,我已经删除了一次答案,但我只是把它作为参考,有人可以采用不同的方法,我只使用 fillna 方法。谢谢
    • 我删除了所有方法并根据问题进行了更新
    猜你喜欢
    • 1970-01-01
    • 2020-12-27
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2021-12-20
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多