gpt4 book ai didi

python Pandas : transforming - moving values from diagonal

转载 作者:太空狗 更新时间:2023-10-30 00:07:09 25 4
gpt4 key购买 nike

给定以下 DataFrame,分组为:

    dataset = z.groupby(
['app', 'regmonth', 'loginsmonth']).sum().unstack().fillna(
0, inplace=False)


cnt
loginsmonth 2014-02-01 2014-03-01 2014-04-01 2014-05-01
app regmonth
1 2014-02-01 6069 1837 107 54
2014-03-01 0 10742 2709 1394
2014-04-01 0 0 5584 1107
2014-05-01 0 0 0 3044
2014-06-01 0 0 0 0

我想将其转换为:

                             cnt                                      
loginsmonth 2014-02-01 2014-03-01 2014-04-01 2014-05-01
app regmonth
1 2014-02-01 6069 1837 107 54
2014-03-01 10742 2709 1394 0
2014-04-01 5584 1107 0 0
2014-05-01 3044 0 0 0
2014-06-01 0 0 0 0

因此,它将对角线移动到行的开头并用零填充空白。panda有什么简单的方法吗?

最佳答案

但是您在此过程中正在更改数据,对吗?

我不知道 pandas 是否有好的方法,但是 np.diagnoal 可以在这里做你想做的事:

In [96]:

print df
loginsmonth 2014-02-01 2014-03-01 2014-04-01 2014-05-01
app regmonth
1 2014-02-01 6069 1837 107 54
2014-03-01 0 10742 2709 1394
2014-04-01 0 0 5584 1107
2014-05-01 0 0 0 3044
2014-06-01 0 0 0 0

[5 rows x 4 columns]
In [124]:

print df*0+np.asarray([np.hstack((np.diagonal(df.values, i), np.zeros(i+1, int)))
for i in range(df.shape[1])]).T
loginsmonth 2014-02-01 2014-03-01 2014-04-01 2014-05-01
app regmonth
1 2014-02-01 6069 1837 107 54
2014-03-01 10742 2709 1394 0
2014-04-01 5584 1107 0 0
2014-05-01 3044 0 0 0
2014-06-01 0 0 0 0

[5 rows x 4 columns]

这里 np.zeros(i+1, int) 中的 1df.shape[0]-df.shape[1]。我不知道你是否会遇到 df.shape[0]<df.shape[1] 的情况。

但是如果您的 DataFrame 看起来总是像这里显示的那样,它就像一个内部没有 0 的上对角矩阵,您可以走捷径:

In [134]:

print df.apply(lambda x: sorted(x, key=lambda y: y==0), axis=1)
cnt 2014-02-01 2014-03-01 2014-04-01 2014-05-01
app regmonth
1 2014-02-01 6069 1837 107 54
2014-03-01 10742 2709 1394 0
2014-04-01 5584 1107 0 0
2014-05-01 3044 0 0 0
2014-06-01 0 0 0 0

[5 rows x 4 columns]

关于 python Pandas : transforming - moving values from diagonal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24044492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com