1
我使用apply
象下面這樣::大熊貓應用功能的Python:我的數據幀<code>my_df</code>上InvalidIndexError
my_df['column_C'] = my_df.apply(lambda x : 'hello' if x['column_B'] is None else x['column_B'])
我想:
if x['column_B'] = None -> return 'hello'
if x['column_B'] != None -> return x['column_B']
然後我得到了以下錯誤:
<ipython-input-31-aa087c9a635e> in <lambda>(x)
----> 1 my_df['column_C'] = my_df.apply(lambda x : 'hello' if x['column_B'] is None else x['column_B'])
/usr/local/lib/python3.4/dist-packages/pandas/core/series.py in __getitem__(self, key)
599 key = com._apply_if_callable(key, self)
600 try:
--> 601 result = self.index.get_value(self, key)
602
603 if not is_scalar(result):
/usr/local/lib/python3.4/dist-packages/pandas/indexes/base.py in get_value(self, series, key)
2187 # python 3
2188 if is_scalar(key): # pragma: no cover
-> 2189 raise IndexError(key)
2190 raise InvalidIndexError(key)
2191
IndexError: ('column_B', 'occurred at index column_A')
有沒有人知道我在這裏做錯了什麼?
爲什麼不是:'my_df ['column_C'] = my_df ['column_C']。fillna('hello')'? – MaxU
這肯定是一個更聰明的方法謝謝!仍然對應用函數中的錯誤感到好奇,儘管... – Edamame