df = pd.DataFrame({'x':[1,2,3,4,5,6],'y':[7,8,9,10,11,12],'z':['a','a','a','b','b','b']})
i = pd.Index([0,3,5,10,20])
i
中的索引来自更大的数据帧,df
是该更大数据帧的子集。所以 i
中会有索引,而 df
中没有。当我做的时候
df.groupby('z').aggregate({'y':lambda x: sum(x.loc[i])}) #I know I can just use .aggregate({'y':sum}), this is just an example to illustrate my problem
我得到了这个输出
y
z
a NaN
b NaN
还有警告信息
__main__:1: FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
如何避免此警告消息并获得正确的输出?在我的示例中,df
的唯一有效索引是 [0,3,5]
,因此预期输出为:
y
z
a 7 #"sum" of index 0
b 22 #sum of index [3,5]
编辑
这里的答案很好,但它们不允许 x
和 y
列的不同类型的聚合。例如,假设我想对 x
的所有元素求和,但对于 y
只对索引 i
中的元素求和:
df.groupby('z').aggregate({'x':sum, 'y': lambda x: sum(x.loc[i])})
这是期望的输出:
y x
z
a 7 6
b 22 15
最佳答案
编辑更新的问题:
df.groupby('z').agg({'x':'sum','y':lambda r: r.reindex(i).sum()})
输出:
x y
z
a 6 7
b 15 22
使用 reindex
,只从 i 中选择那些索引,然后使用 dropna
删除所有那些 nans,因为 i 中的索引不在 df 中。然后是groupyby
和agg
:
df.reindex(i).dropna(how='all').groupby('z').agg({'y':'sum'})
或者,你真的不需要删除:
df.reindex(i).groupby('z').agg({'y':'sum'})
输出:
y
z
a 7.0
b 22.0
关于python - 与数据框中不存在的索引聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54907215/