【问题标题】:Imputing a row with other row if one column is same如果一列相同,则将一行与另一行进行插补
【发布时间】:2022-11-23 17:07:59
【问题描述】:

我有一个数据框

data = [[1000, 'x', 'A'], [2000,'y', 'A'], ['NaN','NaN', 'A'], ['NaN','NaN','B'], [1700,'z', 'B']]

df = pd.DataFrame(data, columns=['Price', 'Attribute', 'Model' ])

现在我想以这样一种方式估算空值:如果模型相同,则将价格最低的行的内容复制到具有空值的行。

输出应该看起来像

data = [[1000, 'x', 'A'], [2000,'y', 'A'], [1000, 'x', 'A'], [1700,'z','B'], [1700,'z', 'B']]
  
df = pd.DataFrame(data, columns=['Price', 'Attribute', 'Model' ])

我试过groupby并关注了Merge two duplicate rows with imputing values from each other

但它没有用。有人可以帮忙吗

【问题讨论】:

    标签: python pandas dataframe numpy group-by


    【解决方案1】:

    如果有多个列,请使用 DataFrame.fillna,每个组的最小值到新列 GroupBy.transform

    cols = ['Price','Col1']
    df[cols] = df[cols].fillna(df.groupby('Model')[cols].transform('min'))
    print(df)
        Price Attribute Model
    0  1000.0         x     A
    1  2000.0         y     A
    2  1000.0       NaN     A
    3  1700.0       NaN     B
    4  1700.0         z     B
    

    【讨论】:

    • 那么属性列呢,可能会有更多的列,我是否必须分别为每一列做呢?
    • @AayushGupta - 答案已编辑。
    • 谢谢。知道为什么我的图像没有显示在问题中。我可以使用链接访问它们!
    • @AayushGupta - 也许是因为meta.stackoverflow.com/questions/285551/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多