简体   繁体   English

Pandas迭代索引并附加剩余的行

[英]Pandas iterating over index and appending remaining rows

I have the following frame: 我有以下框架:

df = pd.DataFrame(data={'id':[1,2,3],'x':[3,2,1]}).set_index('id')
print df
    x
id   
1   3
2   2
3   1

I need to iterate the rows, so that for each id, we append the remaining rows, eg the output should be: 我需要迭代行,这样对于每个id,我们追加剩余的行,例如输出应该是:

    x
id   
1   3
    2
    1
2   2
    1
3   1

Ideally O(n) solution that generalizes to m columns. 理想情况下, O(n)解决方案推广到m列。

Use list comprehension with slice by positions with iloc for list of DataFrame s and then concat for join all together, last remove second level of MultiIndex : 使用列表理解与切片的位置与iloc list of DataFrame然后concat连接在一起,最后删除第二级MultiIndex

comp = [df.iloc[i:] for i in range(len(df.index))]
df = pd.concat(comp, keys=df.index).reset_index(level=1, drop=True)

print (df)
    x
id   
1   3
1   2
1   1
2   2
2   1
3   1

If need both level s is possible add rename_axis for set MultiIndex name s: 如果需要两个level rename_axis以为set MultiIndex name添加rename_axis

df = pd.concat(comp, keys=df.index).rename_axis(('a','b'))
print (df)
     x
a b   
1 1  3
  2  2
  3  1
2 2  2
  3  1
3 3  1

EDIT: 编辑:

First level dont display repeated values, but no values are lost: 第一级不显示重复值,但不会丢失任何值:

#change default option multi_sparse=True
with pd.option_context('display.multi_sparse', False):
    print (df)

     x
a b   
1 1  3
1 2  2
1 3  1
2 2  2
2 3  1
3 3  1

Something like 就像是

df.groupby(level=0).x.apply(lambda y : (np.arange(y)+1)[::-1]).apply(pd.Series).stack()
Out[320]: 
id   
1   0    3.0
    1    2.0
    2    1.0
2   0    2.0
    1    1.0
3   0    1.0
dtype: float64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM