python里面的pandas_在Python中用pandas分区数据帧

可能有一个更有效的方式(我有一个感觉pandas.crosstab将在这里有用),但这里是我该怎么做:

import numpy as np

import pandas

df = pandas.DataFrame({"a": np.random.random(100),

"b": np.random.random(100),

"id": np.arange(100)})

# Bin the data frame by "a" with 10 bins...

bins = np.linspace(df.a.min(), df.a.max(), 10)

groups = df.groupby(np.digitize(df.a, bins))

# Get the mean of each bin:

print groups.mean() # Also could do "groups.aggregate(np.mean)"

# Similarly, the median:

print groups.median()

# Apply some arbitrary function to aggregate binned data

print groups.aggregate(lambda x: np.mean(x[x > 0.5]))

编辑:因为OP正在询问具体只是b的平均值,通过a中的值,只是做

groups.mean().b

另外,如果你希望索引看起来更好(例如显示间隔作为索引),就像在@ bdiamante的例子中一样,使用pandas.cut而不是numpy.digitize。 (Kudos到bidamante。我没有意识到pandas.cut存在。)

import numpy as np

import pandas

df = pandas.DataFrame({"a": np.random.random(100),

"b": np.random.random(100) + 10})

# Bin the data frame by "a" with 10 bins...

bins = np.linspace(df.a.min(), df.a.max(), 10)

groups = df.groupby(pandas.cut(df.a, bins))

# Get the mean of b, binned by the values in a

print groups.mean().b

这导致:

a

(0.00186, 0.111] 10.421839

(0.111, 0.22] 10.427540

(0.22, 0.33] 10.538932

(0.33, 0.439] 10.445085

(0.439, 0.548] 10.313612

(0.548, 0.658] 10.319387

(0.658, 0.767] 10.367444

(0.767, 0.876] 10.469655

(0.876, 0.986] 10.571008

Name: b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值