Skip to main content
 首页 » 编程设计

python之如何在条件检查时从现有数据框中复制数据框中的选定行 [Python]

2024年10月01日6shihaiming

场景

我有数据帧 df1,它需要根据列表 y_km 缩减为不同的数据帧。 Dataframe df1 保存数据如下:

          0         1         2 
0  3.000000  4.000000  3.000000    
1  3.618555  3.646074  3.923834    
2  2.669256  2.769302  2.897346 
3  4.340775  4.311200  4.341143 

和 y_km 为 [0, 3, 2, 1, 2, 3, 3, 3, 1, 1, 0, 1, 2]

我的代码段

df1 = pd.DataFrame(X) 
df1 = df1.iloc[0:5,:10] 
cl0 = pd.DataFrame() 
cl1 = pd.DataFrame() 
cl2 = pd.DataFrame() 
cl3 = pd.DataFrame() 
 
y_km = list(y_kmeans) 
for i in y_kmeans: 
    rows = df1.iloc[i, :] 
    if i == 0: 
        cl0 = cl0.append(rows, ignore_index=False) 
    elif i == 1: 
        cl1 = cl1.append(rows, ignore_index=False) 
    elif i == 2: 
        cl2 = cl2.append(rows, ignore_index=False) 
    elif i == 3: 
        cl3 = cl3.append(rows, ignore_index=False) 

问题是,我的 clX DFrame 具有与第一次插入时相同的记录。

请您参考如下方法:

你想要.groupby:

In [1]: import pandas as pd 
 
In [2]: import numpy as np 
 
In [3]: df = pd.DataFrame(np.random.randint(0, 100, (13, 3))) 
 
In [4]: df 
Out[4]: 
     0   1   2 
0   73  85  15 
1    4  56   5 
2   30  74   1 
3   93  16   9 
4   94  97  41 
5   37  49  63 
6   28  66  10 
7   74  35   4 
8    1  76  65 
9    5  79  27 
10  54  33  74 
11  99  54  46 
12  67  28  77 

简单地:

In [5]: y_km = [0, 3, 2, 1, 2, 3, 3, 3, 1, 1, 0, 1, 2] 
 
In [6]: dfs = {k:g for k,g in df.groupby(y_km)} 

现在,我已经将数据框放入 dict 中,但您可以随心所欲。我建议不要使用一堆变量,而是将它们放在某种容器中。注意:

In [7]: dfs[0] 
Out[7]: 
     0   1   2 
0   73  85  15 
10  54  33  74 
 
In [8]: dfs[1] 
Out[8]: 
     0   1   2 
3   93  16   9 
8    1  76  65 
9    5  79  27 
11  99  54  46 
 
In [9]: dfs[3] 
Out[9]: 
    0   1   2 
1   4  56   5 
5  37  49  63 
6  28  66  10 
7  74  35   4 
 
In [10]: dfs[2] 
Out[10]: 
     0   1   2 
2   30  74   1 
4   94  97  41 
12  67  28  77