为python pandas中另一列的每个唯一值向列表中的每个元素的列添加行

时间:2020-04-21 10:22:05

标签: python pandas dataframe

我有两个长度不等的列表:

Name = ['Tom', 'Jack', 'Nick', 'Juli', 'Harry']
bId= list(range(0,3)) 

我想构建一个如下所示的数据框:

'Name' 'bId'
Tom   0
Tom   1
Tom   2
Jack  0
Jack  1
Jack  2
Nick  0
Nick  1
Nick  2
Juli  0
Juli  1
JUli  2
Harry 0
Harry 1
Harry 2

请提出建议。

1 个答案:

答案 0 :(得分:1)

itertools.product与DataFrame构造函数一起使用:

p = "/path/to/shape/files"

proj_str_bng = 'PROJCS["British_National_Grid",GEOGCS["GCS_OSGB_1936",DATUM["D_OSGB_1936",SPHEROID["Airy_1830",6377563.396,299.3249646]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",400000.0],PARAMETER["False_Northing",-100000.0],PARAMETER["Central_Meridian",-2.0],PARAMETER["Scale_Factor",0.999601272],PARAMETER["Latitude_Of_Origin",49.0],UNIT["Meter",1.0]]'

proj_str_wgs84 = 'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]'

shp_to_prj <- list.files(paste0(wd, p), pattern = "\\.shp$")

if (!file.exists(paste0(wd,p,"prj_log"))){
write("file, dt", file = paste0(wd,p,"prj_log"))
}

for (i in 1:length(shp_to_prj)) {
  shp_to_prj[[i]] <- paste0(wd, p, str_remove_all(shp_to_prj[[i]], ".shp"), ".prj")
  if(file.exists(shp_to_prj[[i]])) {
    next
  }
  write(proj_str_bng, file = shp_to_prj[[i]])
  write(paste0( shp_to_prj[[i]], ",",Sys.time()), file = paste0(wd,p,"prj_log"), append=TRUE)
}
write(paste0( "^===============================================================^", ",",Sys.time()), file = paste0(wd,p,"prj_log"), append=TRUE)