【问题标题】:python: pandas apply function: InvalidIndexErrorpython:熊猫应用功能:InvalidIndexError
【发布时间】:2017-03-29 22:32:55
【问题描述】:

我在我的数据框my_df 上使用apply,如下所示:

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')
  • 这当然是一种更聪明的方法,谢谢!仍然对 apply 函数出了什么问题感到好奇......

标签: python-3.x pandas apply


【解决方案1】:

您需要应用指定axis=1 以将其应用于每一行,而不是每一列。请参阅DataFrame.apply 上的文档:

axis : {0 or 'index', 1 or 'columns'}, default 0

* 0 or 'index': apply function to each column
* 1 or 'columns': apply function to each row

在您当前的通话中,当它真正使用对应于column_A 的pd.Series 时,它找不到x['column_B']

因此,如果您使用以下内容,它将起作用。

my_df['column_C'] = my_df.apply(lambda x : 'hello' 
                                if x['column_B'] is None
                                else x['column_B'], axis=1)

注意:正如上面评论中所指出的,DataFrame.fillna 更适合此任务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2018-02-16
    • 2018-08-29
    相关资源
    最近更新 更多