繁体   English   中英

在 Pandas DataFrame 中查找具有两列值匹配的连续行对

[英]Finding sequential pairs of rows in pandas DataFrame with value matching in two columns

给定一个像这样的 DataFrame:

n     name  number  time  
0     foo    0       .1
1     foo    3       .15
2     bar    0       .2
3     bar    2       .3
4     foo    1       .4
5     foo    5       .45
6     bar    3       .5
7     bar    4       .55
8     bar    5       .6
9     bar    1       .7

制作这个数据框:

n     name  number  time    n     name  number  time
0     foo    0       .1     2     bar    0       .2
1     foo    3       .15    6     bar    3       .5
4     foo    1       .4     9     bar    1       .7
5     foo    5       .45    8     bar    5       .6

如果数据看起来像这样,我使用 shift 组合了一个解决方案:

n     name  number  time  
0     foo    0       .1
1     bar    0       .15
2     foo    1       .2
3     bar    2       .3
4     foo    3       .4
5     bar    5       .5

但我不能保证原始数据交错'foo'和'bar'。 我需要能够在任何距离上配对。

IIUC 仍然需要groupby然后concat

df=pd.concat([y.reset_index(drop=True).set_index('number') for x , y in df.groupby('name')],axis=1, join='inner').reset_index()
Out[322]: 
   number  n name  time  n name  time
0       0  2  bar   0.2  0  foo  0.10
1       3  6  bar   0.5  1  foo  0.15
2       5  8  bar   0.6  5  foo  0.45
3       1  9  bar   0.7  4  foo  0.40

暂无
暂无

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

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