Pandas向DataFrame添加来自切割的列

3

我需要记录DataFramecut(子区间)上的cut

如果每个cut的子区间边界相同,那么这非常简单。例如:

df = pd.DataFrame({'A':np.random.random(100), 'B':np.random.random(100)})
# Primary bins: quintiles on column A
df['P'] = pd.qcut(df['A'], 5, labels=range(1,6)).astype(int)
# Secondary bins: quartiles on column B
df['Q'] = df.groupby(['P'])['B'].transform(lambda x: pd.qcut(x, 4, labels=range(1,5)))

不过,我无法弄清如何使用转换函数,甚至不知道在每个主要的cut边界不同时,如何将第二个cut值重新放回DataFrame中。例如:

subBinBounds = [[0, .1, .5, 1],[0, .3, .6, 1],[0, .2, .7, 1],[0, .4, .6, 1][0, .2, .5, 1]]
for i in range(5):
    cut = df[df['P'] == i+1]  # P is in {1, 5}
    subbin = pd.cut(cut['B'], subBinBounds[i], labels=range(1,4))
    cut['Q'] = cut.assign(Q=subbin.values)
    # But how do we get 'Q' back into df?
1个回答

3
您可以将循环中附加到sers(Series列表)的subseries使用concat连接起来。
#for testing - get same output of random functions
np.random.seed(100)
df = pd.DataFrame({'A':np.random.random(100), 'B':np.random.random(100)})
# Primary bins: quintiles on column A
df['P'] = pd.qcut(df['A'], 5, labels=range(1,6)).astype(int)

sers = []
subBinBounds = [[0, .1, .5, 1],[0, .3, .6, 1],[0, .2, .7, 1],[0, .4, .6, 1], [0, .2, .5, 1]]
for i in range(5):
    cut = df[df['P'] == i+1]
    subbin = pd.cut(cut['B'], subBinBounds[i], labels=range(1,4))
    sers.append(subbin)

df['Q'] = pd.concat(sers)
print (df.head(10))
          A         B  P  Q
0  0.543405  0.778289  3  3
1  0.278369  0.779598  2  3
2  0.424518  0.610328  3  2
3  0.844776  0.309000  5  2
4  0.004719  0.697735  1  3
5  0.121569  0.859618  1  3
6  0.670749  0.625324  4  3
7  0.825853  0.982408  5  3
8  0.136707  0.976500  1  3
9  0.575093  0.166694  3  1

嗯,我不知道问题出在哪里,但如果我使用 range(1, 6),我会得到 IndexError: list index out of range。你这边可以正常工作吗? - jezrael
没错,你也可以使用 range(5),请参考编辑后的答案。 - jezrael
@feetwet - 谢谢。 - jezrael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接