在空的pandas DataFrame上调用apply()

时间:2013-11-14 22:56:21

标签: python pandas

我对pandas DataFrame的apply()方法有疑问。我的问题是apply()可以返回Series或DataFrame,具体取决于输入函数的返回类型;但是,当框架为空时,apply()(几乎)总是返回一个DataFrame。因此,我无法编写需要系列的代码。这是一个例子:

import pandas as pd

def area_from_row(row):
    return row['width'] * row['height']

def add_area_column(frame):
    # I know I can multiply the columns directly, but my actual function is
    # more complicated.
    frame['area'] = frame.apply(area_from_row, axis=1)

# This works as expected.
non_empty_frame = pd.DataFrame(data=[[2, 3]], columns=['width', 'height'])
add_area_column(non_empty_frame)

# This fails!
empty_frame = pd.DataFrame(data=None, columns=['width', 'height'])
add_area_column(empty_frame)

有没有一种标准的处理方法?我可以做到以下几点,但这很愚蠢:

def area_from_row(row):
    # The way we respond to an empty row tells pandas whether we're a
    # reduction or not.
    if not len(row):
        return None
    return row['width'] * row['height']

(我使用pandas 0.11.0,但我也在0.12.0-1100-g0c30665上检查了这一点。)

1 个答案:

答案 0 :(得分:3)

您可以将result_type中的apply参数设置为“减少”。

documentation

默认情况下(result_type = None),从应用函数的返回类型推断出最终的返回类型。否则,它取决于result_type参数。

然后

“ reduce”:如果可能,返回一个Series而不是扩展类似列表的结果。这与“展开”相反。

在您的代码中,在此处更新:

def add_area_column(frame):
    # I know I can multiply the columns directly, but my actual function is
    # more complicated.
    frame['area'] = frame.apply(area_from_row, axis=1, result_type='reduce')