gpt4 book ai didi

python - 在循环中修改 pandas 数据帧的条目

转载 作者:太空宇宙 更新时间:2023-11-03 15:44:11 24 4
gpt4 key购买 nike

我想添加数据框中每条记录的概率,因为我使用了 for 循环

def map_score(dataframe,customers,prob):
dataframe['Propensity'] = 0
for i in range(len(dataframe)):
for j in range(len(customers)):
if dataframe['Client'].iloc[i] == customers[j]:
dataframe["Propensity"].iloc[i] = prob[j]

我能够正确映射与每个客户端关联的概率,但 Python 会抛出警告消息

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy from ipykernel import kernelapp as app

当我使用 .loc 函数时,结果是错误的并且我得到空值。请建议一个有条件更新和添加条目的好方法

最佳答案

您正在尝试对副本进行分配。
dataframe["Propensity"] 是一列,但却是 dataframe 的“副本”。

但是,您正在使用 i 跟踪索引位置。那么,当您有列名 "Propensity" 和索引位置 i 时,如何使用 .loc

分配一些变量,例如idx,等于该位置的dataframe.index

idx = dataframe.index[i]

然后您可以将 .loc 与作业一起使用,不会出现任何问题

dataframe.loc[idx, "Propensity"] = prob[j]
<小时/>
def map_score(dataframe,customers,prob):
dataframe['Propensity'] = 0
for i in range(len(dataframe)):
idx = dataframe.index[i]
for j in range(len(customers)):
if dataframe['Client'].iloc[i] == customers[j]:
dataframe.loc[idx, "Propensity"] = prob[j]

关于python - 在循环中修改 pandas 数据帧的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41911836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com