![](/img/trans.png)
[英]Search Dataframe in r for string using predefined table and add corresponding column
[英]Can't reference column by using predefined parameter as part of string
我有一個數據集,我想通過使用預定義參數作為字符串的一部分來引用我的列。 這樣做的原因是我要保留的列會根據一年中的時間和年份而變化。
我的參數是:
year = '20'
這工作正常並給我想要的結果:
df.['Q1 FY20'] = df.['Q1 FY20'].astype('int32')
但是當我嘗試用我的參數替換字符串中的“20”時,我得到 KeyError: 'Q1 FY20':
df.['Q1 FY' + year] = df.['Q1 FY' + year].astype('int32')
我真的不明白這個,因為我已經檢查過:
type('Q1 FY20') == type('Q1 FY' + year)
'Q1 FY20' == 'Q1 FY' + year
...他們都是真的。 我究竟做錯了什么?
這是完整的錯誤消息:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2896 try:
-> 2897 return self._engine.get_loc(key)
2898 except KeyError:
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: 'Q1 FY20'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-474-3a24ee57971a> in <module>
----> 1 df['Q1 FY' + year] = df['Q1 FY' + year].astype('int32')
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/frame.py in __getitem__(self, key)
2993 if self.columns.nlevels > 1:
2994 return self._getitem_multilevel(key)
-> 2995 indexer = self.columns.get_loc(key)
2996 if is_integer(indexer):
2997 indexer = [indexer]
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2897 return self._engine.get_loc(key)
2898 except KeyError:
-> 2899 return self._engine.get_loc(self._maybe_cast_indexer(key))
2900 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2901 if indexer.ndim > 1 or indexer.size > 1:
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: 'Q1 FY20'
```
我發現了我的錯誤,我試圖在執行所需的數據清理之前在一個實例中測試代碼。
當我用我的參數替換實際代碼時,它起作用了。 但是,我仍然不明白為什么在寫出完整字符串時沒有收到任何 KeyError。
非常感謝大家!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.