拆分熊猫据帧到基于列的条件多dataframes

问题描述 投票:0回答:3

要正确预习我的数据的ML任务,我需要能够到我原来的数据帧分割成多个小dataframes。我想获得所有上述和包括行其中对于列“BOOL”的值是1的行 - 为1即n dataframes其中n是1 OCCURENCES的数量每次出现。

的数据的示例:

df = pd.DataFrame({"USER_ID": ['001', '001', '001', '001', '001'],
'VALUE' : [1, 2, 3, 4, 5], "BOOL": [0, 1, 0, 1, 0]})

预期输出是2个dataframes如下所示:

enter image description here

和:

enter image description here

我曾经考虑一个使用if-else语句追加行中循环 - 但是它对于数据集,我使用效率非常低。寻找这样做的更pythonic的方法。

python pandas dataframe
3个回答
3
投票

您可以使用np.split它接受指数哪里拆分的数组:

np.split(df, *np.where(df.BOOL == 1))

如果你想包括与BOOL == 1到先前数据帧的行可以只加1,所有的指标:

np.split(df, np.where(df.BOOL == 1)[0] + 1)

3
投票

我想使用循环是更好地在这里

idx=df.BOOL.nonzero()[0]

d={x : df.iloc[:y+1,:] for x , y in enumerate(idx)}
d[0]
   BOOL USER_ID  VALUE
0     0     001      1
1     1     001      2

2
投票

为什么不列出理解?喜欢:

>>> l=[df.iloc[:i+1] for i in df.index[df['BOOL']==1]]
>>> l[0]
   BOOL USER_ID  VALUE
0     0     001      1
1     1     001      2
>>> l[1]
   BOOL USER_ID  VALUE
0     0     001      1
1     1     001      2
2     0     001      3
3     1     001      4
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.