python-3.x - python : pandas apply function: InvalidIndexError

标签 python-3.x pandas apply

我在我的数据框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')

有人知道我在这里做错了什么吗?

最佳答案

您需要指定 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更适合此任务。

关于python-3.x - python : pandas apply function: InvalidIndexError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40620072/

相关文章:

python - Total_ordering 和类继承

Python - 返回具有唯一键 :Value pair 的字典列表

python-3.x - Pandas dataframe if else 条件基于前几行

python - 使用 pandas 添加带有 "to_csv"的评论

python - 使用 Pandas 连接向数据框添加一列

python - 如何从列表中删除重复的单词?

python - 使用 pandas 比较两个数据帧以返回新数据帧 - Python

python - 如何使用 apply 两个 pandas 列(包括列表)来使用另一列中的元素返回一列列表中的索引?

python - 将函数应用于数据框

python - 应用以属性系列作为参数的函数