在 pandas 中给定以下数据框:
import numpy as np
df = pandas.DataFrame({"a": np.random.random(100), "b": np.random.random(100), "id": np.arange(100)})
在每个点都由一个a
和b
值组成的id
存在的情况下,如何将a
和b
分入指定的一组箱中(以便我可以然后在每个箱中取a
和b
的中位数/平均值)?对于df
来说,在df
的任意给定行中,a
或b
(或两者都有)可能具有NaN
值。
以下是使用Joe Kington的解决方案并带有更实际的df
的更好示例。我不确定如何访问下面每个df.a
组的df.b
元素:
a = np.random.random(20)
df = pandas.DataFrame({"a": a, "b": a + 10})
# bins for df.a
bins = np.linspace(0, 1, 10)
# bin df according to a
groups = df.groupby(np.digitize(df.a,bins))
# Get the mean of a in each group
print groups.mean()
## But how to get the mean of b for each group of a?
# ...
b
值怎么办?我相信groups.mean()
只会给出a
的平均值。 - user248237a
和b
的平均值(或者更确切地说,它给出了按照a
中的值分组后b
的平均值,这也是我认为你所要求的)。 - Joe Kingtongroups.mean()
返回一个DataFrame
,所以你可以使用groups.mean()["b"]
来访问按a
分组后b
的平均值。 - bdiamante