您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python-2.7 – Pandas:基于空行拆分数据框

5b51 2022/1/14 8:23:04 python 字数 2773 阅读 584 来源 www.jb51.cc/python

我有以下数据框架. id A B C 1 34353 917998 x 2 34973 980340 x 3 87365 498097 x 4 98309 486547 x 5 87699

概述

id       A        B        C   
1      34353    917998     x        
2      34973    980340     x      
3      87365    498097     x      
4      98309    486547     x      
5      87699    475132         
6      52734    4298894         
7      8749267  4918066    x    
8      89872    18103         
9      589892   4818086    y    
10     765      4063       y 
11     32369    418165     y
12     206      2918137    
13     554      3918072    
14     1029     1918051    x
15     2349243  4918064

对于每组空行,例如5,6我想创建一个新的数据框.需要生成多个数据帧.如下所示:

id      A        B
5      87699    475132         
6      52734    4298894
id      A        B
8      89872    18103      
id      A        B
12     206      2918137    
13     554      3918072          
id      A        B
15     2349243  4918064          
isnull = df.C.isnull()
partitions = (isnull != isnull.shift()).cumsum()

gb = df[isnull].groupby(partitions)

此时,我们已经完成了为df中每个连续NaN组创建单独数据帧的目标.对于gb.groups中的每个键,可以通过gb.get_group()方法访问它们

为了验证,我们将连接显示.

keys = gb.groups.keys()
dfs = pd.concat([gb.get_group(g) for g in keys],keys=keys)
dfs

设置为df

我使用了@Alberto Garcia-Raboso的读者

import io
import pandas as pd

# Create your sample dataframe
data = io.StringIO("""\
id       A        B        C   
1      34353    917998     x        
2      34973    980340     x      
3      87365    498097     x      
4      98309    486547     x      
5      87699    475132         
6      52734    4298894         
7      8749267  4918066    x    
8      89872    18103         
9      589892   4818086    y    
10     765      4063       y 
11     32369    418165     y
12     206      2918137    
13     554      3918072    
14     1029     1918051    x
15     2349243  4918064
""")
df = pd.read_csv(data,delim_whitespace=True)

总结

以上是编程之家为你收集整理的python-2.7 – Pandas:基于空行拆分数据框全部内容,希望文章能够帮你解决python-2.7 – Pandas:基于空行拆分数据框所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶