我想在dataframe positions_deposits中添加一个计算出的字段“得分”。
当我对熊猫的dataframe positions_deposits运行以下操作时,
for i in range(len(positions_deposits)):
<Read some values from the dataframe which would be passed to a function in the next line>
Score = RAG_function (Amber_threshold, Red_threshold, Type_threshold, Values)
positions_deposits['Score'].loc[i] = Score我得到以下错误。请你引导我克服我所犯的错误,以及如何解决它?
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~/.local/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2894 try:
-> 2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Score'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-201-7d0481b84aa4> in <module>
6 Values = positions_deposits['Values'].loc[i]
7 # Score = RAG_function (Amber_threshold, Red_threshold, Type_threshold, Values)
----> 8 positions_deposits["Score"].loc[i] = RAG_function (Amber_threshold, Red_threshold, Type_threshold, Values)
9
10 # print("Score is %i.00" %Score)
~/.local/lib/python3.8/site-packages/pandas/core/frame.py in __getitem__(self, key)
2904 if self.columns.nlevels > 1:
2905 return self._getitem_multilevel(key)
-> 2906 indexer = self.columns.get_loc(key)
2907 if is_integer(indexer):
2908 indexer = [indexer]
~/.local/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
-> 2897 raise KeyError(key) from err
2898
2899 if tolerance is not None:
KeyError: 'Score'请注意:如果我print(Score),没有错误。这意味着函数,RAG_function正在被执行,但是数据文件失败了。
谢谢!
发布于 2020-11-27 07:44:03
您可能想了解一下.loc和.iloc是如何工作的。但话虽如此,还有另一种更好的办法:
import pandas
import random
df = pandas.DataFrame([{"A": random.randint(0,100), "B": random.randint(0,100)} for _ in range(100)])
def rag_function(row):
A = row["A"]
B = row["B"]
return A * B
df["Score"] = df.apply(rag_function, axis=1)注意:我没有您的RAG_function,所以我创建了一些随机函数。其思想是将此函数应用于数据仓库中的每个row。
https://stackoverflow.com/questions/65015802
复制相似问题