加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:31:37 所属栏目:Python 来源:网络整理
导读:我有以下数据框架. 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 y12 206 2918137 13 554 3918072
我有以下数据框架.
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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读