Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在循环中修改数据帧的条目_Python_Loops_Pandas_Dataframe - Fatal编程技术网

Python 在循环中修改数据帧的条目

Python 在循环中修改数据帧的条目,python,loops,pandas,dataframe,Python,Loops,Pandas,Dataframe,我想为我使用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[

我想为我使用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会抛出一条警告消息

试图在数据帧切片的副本上设置值。 尝试改用.loc[row\u indexer,col\u indexer]=value

请参阅文档中的注意事项: 从ipykernel导入内核应用程序作为应用程序

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

您正在尝试对副本进行赋值。
dataframe[“倾向性”]
是一列,但却是
dataframe的“副本”

但是,您正在使用
i
跟踪索引位置。那么,当您有一个列名
“倾向性”
和一个索引位置
i
时,如何使用
.loc

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

idx = dataframe.index[i]
然后,您可以将
.loc
与作业一起使用,而不存在任何问题

dataframe.loc[idx, "Propensity"] = prob[j]


非常感谢,我现在明白了。在这种情况下,有没有办法避免循环中的循环。我基本上希望将dataframe.clients与包含客户端的数组相匹配,概率数组的顺序与客户端数组相同。所以基本上我想把概率加到客户匹配的指数上,这个问题是关于警告的。我想问另一个关于循环的问题。当您这样做时,请添加一些样本数据,以便我们可以看到您看到的内容。谢谢piRSquared,我感谢您的宝贵反馈:)
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]