【问题标题】:Adding calculated constant value into Python data frame将计算出的常量值添加到 Python 数据框中
【发布时间】:2017-01-22 16:36:50
【问题描述】:

我是 Python 新手,我相信这是一个非常基本的问题(对此感到抱歉),但我试图在这里寻找解决方案:Better way to add constant column to pandas data frame 和这里:add column with constant value to pandas dataframe 以及许多其他地方.. .

我有一个像这样的“玩具”样本的数据框:

A    B  
10   5
20   12
50   200

我想添加新列 (C),这将是 A 和 B (50/200) 的最后一个数据单元格的划分;所以在我的例子中,我想得到:

A    B    C
10   5    0.25 
20   12   0.25
50   200  0.25

我尝试使用此代码:

groupedAC ['pNr'] = groupedAC['cIndCM'][-1:]/groupedAC['nTileCM'][-1:]

但我只在最后一个单元格中得到结果(我相信这是我的代码充当“指针”而不是数字的结果 - 但正如我所说,我试图将我的结果“转换”为一个常量(即使使用 temp 变量)但没有成功)。

您的帮助将不胜感激!

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您需要使用.iloc[-1]而不是.iloc[-1:]对其进行索引,因为后者返回一个Series,因此在分配回数据框时,需要匹配索引:

    df.B.iloc[-1:]                         # return a Series
    #2    150
    #Name: B, dtype: int64
    
    df['C'] = df.A.iloc[-1:]/df.B.iloc[-1:] # the index has to be matched in this case, so only
                                            # the row with index = 2 gets updated   
    df
    #   A   B   C
    #0  10  5   NaN
    #1  20  12  NaN
    #2  50  200 0.25
    
    df.B.iloc[-1]                          # returns a constant
    # 150
    
    df['C'] = df.A.iloc[-1]/df.B.iloc[-1]  # there's nothing to match when assigning the 
                                           # constant to a new column, the value gets broadcasted   
    df
    #   A   B   C
    #0  10  5   0.25
    #1  20  12  0.25
    #2  50  200 0.25
    

    【讨论】:

    • 当我使用groupedAC['cIndCM'][-1:]/groupedAC['nTileCM'][-1:] 时,我得到一个数字(0.027...)。但是当我使用groupedAC.cIndCM.iloc[-1]/groupedAC.nTileCM.iloc[-1] 时,我得到了零……我做错了吗?
    • 这里的groupedAC 是什么?它是一个分组对象吗?你能说明你是如何得到groupedAC的吗?
    • groupedAC = acData.groupby(by="Ntile_Cust_By_Product")["ClickIND"].agg(['size', 'sum']) 之后,我将插入更多(新)列,这些列是根据 basic 数据框计算得出的
    • 如果您的groupedAC 来自此代码,那么它没有cIndCMnTileCM 列,我认为您的意思是其他一些数据框。
    • 这些列是:groupedAC ['nTileCM'] = groupedAC["size"].cumsum()groupedAC ['cIndCM'] = groupedAC["sum"].cumsum()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2015-07-09
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多