【问题标题】:Replace the missing value NAN based on values of another columns (conditions)根据另一列(条件)的值替换缺失值 NAN
【发布时间】:2020-11-15 13:45:43
【问题描述】:

您好,我想根据来源的值填写 NaN 值。 我试过np.select,但是这个方法也会覆盖其他正确的值。

landline_area1['area'] = np.select(area_conditions, values)

  • 表格概览
source  codes       area
4   1304    1304    Dover
5   1768    1768    Penrith
6   2077    NaN     NaN
7   1225    1225    Bath
8   1142    NaN     NaN
  • 条件
area_conditions = [
    (landline_area1['source'].str.startswith('20')),
    (landline_area1['source'].str.startswith('23')),
    (landline_area1['source'].str.startswith('24'))]
  • 价值观
values = [
    'London',
    'Southampton / Portsmouth',
    'Coventry']
  • 预期结果
source  codes       area
4   1304    1304    Dover
5   1768    1768    Penrith
6   2077    NaN     London
7   1225    1225    Bath
8   1142    NaN     Sheffield

【问题讨论】:

    标签: python python-3.x pandas dataframe missing-data


    【解决方案1】:

    让我们试试np.select 并添加 astype str

    #landline_area1['source'].astype(str).str.startswith('20')
    
    s = np.select(area_conditions, values)
    landline_area1['area'].fillna(pd.Series(s, index=landline_area1.index),inplace=True)
    

    【讨论】:

    • 这行得通!我想澄清一下: 1. 它使用 np.select 将条件和值存储为数组? 2.fillna是补缺失值的我不太明白pd.series的用法-这是定位索引吗?
    • @JamesHuang 是的,那是 array 也不是 serise ,所以你不能填充~
    猜你喜欢
    • 2019-12-02
    • 2015-12-31
    • 2019-05-12
    • 2020-05-16
    • 2018-11-29
    • 2018-09-16
    • 2012-11-06
    • 2021-04-13
    • 2014-06-09
    相关资源
    最近更新 更多