Python中的表操作(转换现有的R代码)

2024-10-06 10:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

寻找一些在python或arcpy中操作表的技巧。在一列中,我有流段的ID值,在第二列中是它们所属组的ID值。如果段属于多个组,我想将所有“额外”组替换为一个组值。我知道如何在R中做到这一点,并附上了代码,但我希望能够在Python中做到这一点。任何帮助都是非常感谢的。在

#-----In Python get the vectors I'm interested in...
ORIDs=[]     #empty vector to record stream segment IDs
GRPs=[]     #empty vector to record segment groups
SC = arcpy.SearchCursor("feature.lyr")      #Search cursor to get FIDS
for row in SC:
    ORIDs.append(row.getValue("ORIG_FID"))
    GRPs.append(row.getValue("FEAT_SEQ"))
del row
del SC

#-----At this point I'm lost but can do what I want in R (R code as follows)
ORIDs<-c(2, 7, 8, 9, 9, 10, 11, 11, 12, 13, 14, 15, 16, 18, 19, 21, 23, 
    23, 25, 26, 27, 28, 29, 30, 32, 33, 34, 34, 35, 35, 36, 37, 38,
        39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 45, 45, 46, 46, 47, 47, 
    48, 49, 50, 51, 52, 52, 53, 53, 54, 55, 57, 58, 59, 60, 61, 63, 
    64, 65, 66, 66, 67, 67, 68, 68, 69, 69, 70, 71, 73, 74, 74, 75, 
    76, 76, 77, 78, 79, 80)

GRPs<-c(1, 2, 1, 3, 1, 4, 4, 5, 3, 5, 6, 4, 5, 7, 8, 3, 8, 7, 9, 8, 
    10, 10, 9, 10, 11, 11, 11, 12, 7, 13, 9, 13, 14, 14, 14, 15, 
    12, 2, 15, 12, 13, 16, 17, 2, 6, 16, 17, 17, 18, 15, 6, 19, 
    20, 18, 20, 20, 21, 22, 21, 23, 18, 21, 23, 22, 16, 22, 24, 
    24, 25, 19, 26, 19, 26, 26, 27, 24, 27, 23, 25, 27, 28, 29, 
    25, 29, 28, 28, 29)

dat<-data.frame(ORID=ORIDs,GRP=GRPs)

uniq.orid<-unique(dat$ORID)

for(i in uniq.orid){
    tgrp<-unique(dat[dat$ORID==i,"GRP"])
    if(length(tgrp)>1){
        dat[dat$GRP %in% tgrp,"GRP"]=tgrp[1]
    }
}

write.table(dat,"D:/StreamConn/smallnetwork/simple.groups.csv",row.names=F,sep=",")

Tags: toinidgetdatemptyrowsc
1条回答
网友
1楼 · 发布于 2024-10-06 10:23:48

感谢您推荐熊猫贝罗。我想我该怎么处理那个包裹了。Python代码如下:

import pandas as pd

ORIDs=[2, 7, 8, 9, 9, 10, 11, 11, 12, 13, 14, 15, 16, 18, 19, 21, 23, 
    23, 25, 26, 27, 28, 29, 30, 32, 33, 34, 34, 35, 35, 36, 37, 38,
        39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 45, 45, 46, 46, 47, 47, 
    48, 49, 50, 51, 52, 52, 53, 53, 54, 55, 57, 58, 59, 60, 61, 63, 
    64, 65, 66, 66, 67, 67, 68, 68, 69, 69, 70, 71, 73, 74, 74, 75, 
    76, 76, 77, 78, 79, 80]

GRPs=[1, 2, 1, 3, 1, 4, 4, 5, 3, 5, 6, 4, 5, 7, 8, 3, 8, 7, 9, 8, 
    10, 10, 9, 10, 11, 11, 11, 12, 7, 13, 9, 13, 14, 14, 14, 15, 
    12, 2, 15, 12, 13, 16, 17, 2, 6, 16, 17, 17, 18, 15, 6, 19, 
    20, 18, 20, 20, 21, 22, 21, 23, 18, 21, 23, 22, 16, 22, 24, 
    24, 25, 19, 26, 19, 26, 26, 27, 24, 27, 23, 25, 27, 28, 29, 
    25, 29, 28, 28, 29]

uniq_orid = list(set(ORIDs))

tab=pd.DataFrame({'ORID':ORIDs,'GRP':GRPs})

for i in uniq_orid:
    tgrp = list(tab[(tab['ORID']==i)]['GRP'])
    if(len(tgrp)>1):
        tab['GRP'][tab['GRP'].isin(tgrp)]=tgrp[0]

相关问题 更多 >