Skip to main content
 首页 » 编程设计

python之当 "value in column X"更改时提取 Pandas 数据帧 block

2024年09月07日19小虾米

我有一个包含约 30 列和 100 000 行的数据框 df。我想根据特定单元格的值拆分数据帧(并最终将数据提取到 np.arrays)。

示例

给定以下数据框

   C1 C2 C3 C4 
 0  0  0  0  0 
 1  0  0  1  0 
 2  0  0  1  0 
 3  0  0  2  0 
 4  0  0  2  0 
 5  0  0  2  0 
 6  0  0  0  0 
 7  0  0  1  0 
 8  0  0  3  0 
 9  0  0  5  0 
10  0  0  2  0 
11  0  0  2  0 
12  0  0  2  0 

我想在 C3 列从 2 更改时拆分它。 IE。在第 5 行之后,第 0-5 行成为一个数据帧(或 np.array),第 6-12 行成为另一个数据帧。结果应该是:

   C1 C2 C3 C4 
 0  0  0  0  0 
 1  0  0  1  0 
 2  0  0  1  0 
 3  0  0  2  0 
 4  0  0  2  0 
 5  0  0  2  0 

和

   C1 C2 C3 C4 
 0  0  0  0  0 
 1  0  0  1  0 
 2  0  0  3  0 
 3  0  0  5  0 
 4  0  0  2  0 
 5  0  0  2  0 
 6  0  0  2  0 

我的实际数据框中的列具有不同的值(数字或字符串)。

我目前的方法是遍历整个帧并创建一个“索引数组”,我在其中找出如何拆分数据帧。首先,它并没有完全按照我的意愿去做,必须有一种更有效的方法来做到这一点...

def filter_data(df): 
 
    indices = []        # list to hold indices where we are to split the frame 
    counter = -1 
    waiting_for_new_index = True 
 
    for idx, v in df["column_of_interest"].iteritems(): # row index and corresponding value 
 
        if v != 2: 
            waiting_for_new_index = True 
            continue 
        else: 
            if waiting_for_new_index: 
                waiting_for_new_index = False 
                counter += 1 
 
        # Add the counter to the index 
        indices.append(counter) 
 
    return indices 

请您参考如下方法:

您可以使用:

a = (df.C3.eq(2).diff() & df.C3.shift().eq(2)).cumsum() 
print (a) 
0     0 
1     0 
2     0 
3     0 
4     0 
5     0 
6     1 
7     1 
8     1 
9     1 
10    1 
11    1 
12    1 
Name: C3, dtype: int32 
 
dfs = dict(tuple(df.groupby(a))) 
print (dfs) 
{0:    C1  C2  C3  C4 
0   0   0   0   0 
1   0   0   1   0 
2   0   0   1   0 
3   0   0   2   0 
4   0   0   2   0 
5   0   0   2   0, 1:     C1  C2  C3  C4 
6    0   0   0   0 
7    0   0   1   0 
8    0   0   3   0 
9    0   0   5   0 
10   0   0   2   0 
11   0   0   2   0 
12   0   0   2   0} 

详细信息:

df['a'] =  df.C3.eq(2).diff() 
df['b'] = df.C3.shift().eq(2) 
df['c'] = df.a & df.b 
df['d'] = df['c'].cumsum() 
print (df) 
    C1  C2  C3  C4      a      b      c  d 
0    0   0   0   0    NaN  False  False  0 
1    0   0   1   0  False  False  False  0 
2    0   0   1   0  False  False  False  0 
3    0   0   2   0   True  False  False  0 
4    0   0   2   0  False   True  False  0 
5    0   0   2   0  False   True  False  0 
6    0   0   0   0   True   True   True  1 
7    0   0   1   0  False  False  False  1 
8    0   0   3   0  False  False  False  1 
9    0   0   5   0  False  False  False  1 
10   0   0   2   0   True  False  False  1 
11   0   0   2   0  False   True  False  1 
12   0   0   2   0  False   True  False  1