pandas -在 pandas 中为每个组插入空白行 [英] Pandas - Insert blank row for each group in pandas

查看:147
本文介绍了 pandas -在 pandas 中为每个组插入空白行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框

 将pandas导入为pd将numpy导入为npdf1 = pd.DataFrame({'group':[1,1,2,2,2],'value':[2,3,np.nan,5,4]})df1团体价值0 1 21 1 32 2 NaN3 2 54 2 4 

我想在其中 value 的值为 NaN 的每个组之后添加一行.期望输出为:

 组值0 1 21 1 32 1 NaN3 2 NaN4 2 55 2 46 2 NaN 

在我的真实数据集中,除了 value 之外,我还有很多组和更多列,我希望所有这些行在新添加的行中都是 NaN .

非常感谢您的帮助

解决方案

concat append

  s = df1.groupby('group')out = pd.concat([_的i,append({'value':np.nan},ignore_index = True),i in s])out.group = out.group.ffill().astype(int) 

应用追加 [1]

  df1.groupby('group').apply(lambda d:d.append({'group':d.name},ignore_index = True).astype({'group':int})).reset_index(drop = True) 

两种产品:

 组值0 1 2.01 1 3.02 1 NaN3 2 NaN4 2 5.05 2 4.06 2 NaN 


[1] 此解决方案由您当地的 @piRSquared

I have a dataframe

import pandas as pd
import numpy as np
df1=pd.DataFrame({'group':[1,1,2,2,2],
             'value':[2,3,np.nan,5,4]})
df1

    group   value
0   1       2
1   1       3
2   2       NaN
3   2       5
4   2       4

I want to add a row after each group in which the value of value is NaN . The desire output is:

   group   value
0   1       2
1   1       3
2   1       NaN
3   2       NaN
4   2       5
5   2       4
6   2       NaN

In my real dataset I have a lot of groups and more columns besides value, I want all of them to be NaN in newly added row.

Thanks a lot for the help

解决方案

concat with append

s = df1.groupby('group')
out = pd.concat([i.append({'value': np.nan}, ignore_index=True) for _, i in s])
out.group = out.group.ffill().astype(int)

apply with append[1]

df1.groupby('group').apply(
    lambda d: d.append({'group': d.name}, ignore_index=True).astype({'group': int})
).reset_index(drop=True)

Both produce:

   group  value
0      1    2.0
1      1    3.0
2      1    NaN
3      2    NaN
4      2    5.0
5      2    4.0
6      2    NaN


[1] This solution brought to you by your local @piRSquared

这篇关于 pandas -在 pandas 中为每个组插入空白行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆