Skip to main content
 首页 » 编程设计

python之在对应于其他两列的一列中划分两行及其关系(Python)

2025年05月04日16linjiqin

我有一个如下所示的数据框,我想要的是“nom_1”列中的每个元素对其对应的 target_1 到 target_0 进行划分。因此,对于 "Circle","target_1" 的 "id" 是 9168,"id" 是 "target_0"是28152,我需要9168/28152的除法。我可以手动执行此操作,但我需要将其自动化,因为会有更多具有不同唯一值的数据框。

结果我需要创建一个看起来像这样的字典:

{'Circle': 0.3705589911482963, 'Polygon': 0.34775978284076003, 'Square': 0.5312055617001106, 'Star': 0.19850208121615415, 'Trapezoid': 1.5383163853653423}  

注意:这些数字并不代表实际结果,只是我想要的格式

到目前为止,这是我的代码:

    nom_1  target     id 
0      Circle       0  28152 
1      Circle       1   9168 
2     Polygon       0  24741 
3     Polygon       1  11402 
4      Square       0  32787 
5      Square       1  16810 
6        Star       0  31645 
7        Star       1  14259 
8   Trapezoid       0  71833 
9   Trapezoid       1  29348 
10   Triangle       0  19078 
11   Triangle       1  10777 
 
nom_1_dat = train.groupby(["nom_1","target"]).count()[["id"]].reset_index() 
 
print(nom_1_dat) 
 
nom_1_dict = {} 
i_list = [] 
for i,element in enumerate(nom_1_dat["nom_1"]): 
    i_list.append(i) 
for i,element in enumerate(nom_1_dat["nom_1"]): 
    if (i+1) < max(i_list):  
        nom_1_dict[element] = (nom_1_dat["id"][i+1])/(nom_1_dat["id"][i]) 
 
print(nom_1_dict) 

请您参考如下方法:

给定以下数据框:

df=pd.DataFrame([['Circle', 'Circle', 'Polygon', 'Polygon'], [0, 1, 0, 1], [28152, 9168, 24741, 11402]], ['nom_1', 'target', 'id']).T 
     nom_1 target     id 
0   Circle      0  28152 
1   Circle      1   9168 
2  Polygon      0  24741 
3  Polygon      1  11402 

试试这段代码,使用 groupby.agg :

df_res = df.groupby('nom_1').agg({'id': lambda row_id: row_id[1]/row_id[0]}) 

或等同于,使用 groupby.apply :

df_res = df.groupby('nom_1').apply(lambda row: (row[row.target==1]['id'].iloc[0]/row[row.target==0]['id'].iloc[0])) 

在这两种情况下给出:

               id 
nom_1             
Circle   0.325661 
Polygon  0.460854 

如果要将结果转成字典:

dict_res = df_res.to_dict()['id'] 
# output: {'Circle': 0.3256606990622336, 'Polygon': 0.46085445212400467}