gpt4 book ai didi

python - 根据列值将 pandas 数据帧分成 'chunks'

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:13 24 4
gpt4 key购买 nike

解释我试图完成的事情的最好方法可能只是一个例子。给定以下数据框:

     tag  ID
0 0 1
1 0 2
2 1 3
3 1 4
4 0 5
5 1 6
6 0 7
7 0 8
8 1 9
9 1 10
10 0 11
11 0 12
12 0 13
13 1 14
14 1 15
15 1 16
16 0 17

根据标签,将 dataFrame 分成“ block ”。当一个 block 被识别时,它被存储在一个单独的数据帧中(或者可能是一个数据帧列表?)。 “分块”的标准是在标记列中查找 2 个或更多个零。如果有超过 2 个零,则切出存在于先前零和当前零之间的所有数据。

在我上面的示例 dataFrame 中,代码会删除索引行:0,1,6,7,10,11,12...然后它将以下 block 存储到单独的 dataFrame 中:

     tag  ID
2 1 3
3 1 4
4 0 5
5 1 6

tag ID
8 1 9
9 1 10

tag ID
13 1 14
14 1 15
15 1 16
16 0 17

希望一切顺利。抱歉,如果不是...有没有一种好的 pythonic 方法可以在不产生大量循环的情况下完成这个任务?

感谢您的帮助,希杰

最佳答案

已经尽力了...我正在使用另外两个新参数

df['group']=df.tag.diff().fillna(0).ne(0).cumsum()
df1=df.groupby('group').tag.agg([sum,lambda x : len(x)])
dropindex=df1[(df1['sum']==0)&(df1['<lambda>']>1)].index # only drop more than one continue 0
df=df.loc[~df.group.isin(dropindex)]
df['group2']=df.reset_index()['index'].diff().ne(1).cumsum().values
for _, dfyourneed in df.groupby('group2',as_index=False):
print(dfyourneed.drop(['group2','group'],1))

tag ID
2 1 3
3 1 4
4 0 5
5 1 6
tag ID
8 1 9
9 1 10
tag ID
13 1 14
14 1 15
15 1 16
16 0 17

或者你可以将它保存到列表中

[dfyourneed.drop(['group2', 'group'], 1) for _, dfyourneed in df.groupby('group2', as_index=False)]
Out[1083]:
[ tag ID
2 1 3
3 1 4
4 0 5
5 1 6, tag ID
8 1 9
9 1 10, tag ID
13 1 14
14 1 15
15 1 16
16 0 17]

关于python - 根据列值将 pandas 数据帧分成 'chunks',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46677061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com