1

寻找一些在 python 或 arcpy 中操作表格的技巧。在一列中,我有流段的 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=",")
4

1 回答 1

1

感谢您推荐熊猫贝罗。我想出了我需要用那个包做的事情。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]
于 2013-10-10T14:29:21.663 回答