Python 对值介于两个数字之间的行进行计数,并按不同的列分组
我对这件事非常恼火——如果它表现出来,请提前道歉。 *我所有的工作都在一台不同的(工作)电脑上——是的,想象一下这样生活 两列:Python 对值介于两个数字之间的行进行计数,并按不同的列分组,python,pandas,Python,Pandas,我对这件事非常恼火——如果它表现出来,请提前道歉。 *我所有的工作都在一台不同的(工作)电脑上——是的,想象一下这样生活 两列:accountid,amount accountid amount 1 500 2 440 1 420 2 300 结果应该是: accountid count_amount_400_500 1 2 2 1 我试图计算acc
accountid
,amount
accountid amount
1 500
2 440
1 420
2 300
结果应该是:
accountid count_amount_400_500
1 2
2 1
我试图计算accountid的金额在400到500之间的次数,并将其放在单独的列中
我认为像这样的东西,以及其他100个类似的迭代,可以工作:
df.loc[df['amount'].between(400500).groupby('accountid').nunique()
但他们没有
使用
groupby
+agg
df.groupby('accountid').amount.agg(lambda s: s.between(400, 500).sum())
我建议使用
pd.cut
df.groupby([df.accountid,pd.cut(df.amount,[0,400,500,600])]).size()
Out[109]:
accountid amount
1 (400, 500] 2
2 (0, 400] 1
(400, 500] 1
dtype: int64
或者使用交叉表
pd.crosstab(df.accountid,pd.cut(df.amount,[0,400,500,600]))
Out[114]:
amount (0, 400] (400, 500]
accountid
1 0 2
2 1 1
pd.crosstab(df.accountid,pd.cut(df.amount,[0,400,500,600]))
Out[114]:
amount (0, 400] (400, 500]
accountid
1 0 2
2 1 1