python-2.7 – Pandas:基于空行拆分数据框
发布时间:2020-11-18 10:13:27 所属栏目: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 – 什么是django.utils.functional .__ p
- python:re.sub的replace函数不接受额外的参数 –
- python – 将NumPy对象与“None”进行比较时的Fu
- python – Mac上的Jupyter安装失败
- python – sklearn pipeline – 在管道中应用多项
- python – pymongo:MongoClient或Connection
- django 1.5中的自定义用户模型
- 在python中公开C函数并在C中嵌入python
- Python / Scipy – 将optimize.curve_fit的sigma
- python – 管理站点中的默认过滤器
热点阅读