我遇到了关于Pandas数据框的apply()方法的问题。我的问题是apply()方法根据输入函数的返回类型可以返回Series或DataFrame,但当数据框为空时,apply()方法(几乎)总是返回一个DataFrame。因此我不能写期望返回Series的代码。以下是一个例子:
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上检查了一下。
if
从add_area_column
中移除,并将其放在您调用apply
的位置) - Matt