【发布时间】:2019-07-21 06:40:04
【问题描述】:
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
【问题讨论】:
-
预期输出是什么?
-
@jezrael:我已经用预期的输出更新了我的问题
-
索引 5 不在 i 中。
-
df[df.index.isin(i)].groupby('z')['y'].sum() -
@ScottBoston:对不起,你是对的。我已经更新了我的问题