向Python数据fram中添加计算的常量值

2024-10-02 18:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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);因此在我的示例中,我希望得到:

^{pr2}$

我试着用这个代码:

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

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

感谢您的帮助!在


Tags: to数据代码addpandasdatawithcolumn
1条回答
网友
1楼 · 发布于 2024-10-02 18:24:30

您需要用.iloc[-1]而不是.iloc[-1:]为其编制索引,因为后者返回一个序列,因此在分配回数据帧时,需要匹配索引:

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

相关问题 更多 >