如何创建一个从dataframe中提取两个值的函数?
python 230
原文标题 :How do I create a function that pulls two values from my dataframe?
我想创建一个基本上从我的数据框中提取两个特定值或“单元格”的函数。数据框有点大,所以我附上了一张图片。我当前的函数代码
def return_riskscore(CountryA, CountryB):
i = CountryA
j = CountryB
senti_value = main7.at[i,j]
return senti_value
然后我使用以下内容将该函数应用于数据框。
main7["Value"] = main7.apply(return_riskscore(CountryA = 'Ukraine ', CountryB = 'Russia'))
我收到的错误如下:
KeyError Traceback (most recent call last)
/var/folders/bl/qq18pm0d3kv24sfpjxbb_d2w0000gn/T/ipykernel_29770/4285294519.py in <module>
----> 1 main7["Value"] = main7.apply(return_riskscore(CountryA = 'Ukraine', CountryB = 'Russia'))
/var/folders/bl/qq18pm0d3kv24sfpjxbb_d2w0000gn/T/ipykernel_29770/1369879570.py in return_riskscore(CountryA, CountryB)
2 i = CountryA
3 j = CountryB
----> 4 senti_value = main7.at[i,j]
5 return senti_value
6 #for i in range(len(main7)):
~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexing.py in __getitem__(self, key)
2273 return self.obj.loc[key]
2274
-> 2275 return super().__getitem__(key)
2276
2277 def __setitem__(self, key, value):
~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexing.py in __getitem__(self, key)
2220
2221 key = self._convert_key(key)
-> 2222 return self.obj._get_value(*key, takeable=self._takeable)
2223
2224 def __setitem__(self, key, value):
~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/frame.py in _get_value(self, index, col, takeable)
3577
3578 try:
-> 3579 loc = engine.get_loc(index)
3580 return series._values[loc]
3581 except AttributeError:
~/opt/anaconda3/lib/python3.9/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
KeyError: 'Ukraine'
更具体地说,我希望能够拉出 A 国和 B 国的值。还有其他方法可以实现吗?数据框