我有一个名为panel_long的熊猫数据框,看起来像这样:
x y z event Start
company period
A 1 1 2 3 False 5
B 1 1 2 3 False 7
...
A 27 1 2 3 True 5
B 27 1 2 3 False 7
...
A 31 1 2 3 False 5
B 31 1 2 3 True 7
作为livelines生存分析的准备,我想添加一列,指出第一个期间事件对每个公司而言等于True。对于非多索引数据帧,我将使用idxmax,但我无法弄清楚如何使其适用于多索引df。除其他外,我尝试了以下方法:
def funct(df, column):
df[column].idxmax()
df = panel_long.groupby('company').apply(funct, ('event'))
但是那只会返回一个空的数据框。有任何想法吗?我被卡住了
您应该在自定义函数中return
输出
def funct(df, column):
return df[column].idxmax()
df.groupby('company').apply(funct, ('event'))
Out[248]:
company
A (A, 1)
B (B, 1)
dtype: object