如何在Python中将多个唯一元素附加到同一组列中?

2024-05-19 14:43:05 发布

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

我尝试从数据帧中的一列获取唯一标识符/键,并将其附加到另一个数据帧中的两列中的同一组元素。两个数据帧如下:

         df1                              df2
Geogkey    Brand  Week               date       Impressions
TMZ43434   x      6/16/18           6/14/18       798798
KRO36783   y      6/16/18           6/21/18       562314
....                                6/28/18       462534
n

df2中还有几个日期是8月份之前的,但为了简洁起见,我没有将它们包括在内。我想从df1中获取每个惟一的Geogkey并将它们附加到df2中,这样每一行特定的日期和印象都与Geogkey匹配。 df2中的一组日期和印象将不断地在数据帧中重复,每个组合对应于一个唯一的geogkey—每次都会重复。所以最后的数据框是这样的:

Geogkey    date    Impressions
TMZ43434  6/14/18   798798
TMZ43434  6/21/18   562314
TMZ43434  6/28/18   462534
KRO36783  6/14/18   798798
KRO36783  6/21/18   562314
KRO36783  6/28/18   462534

这将对每个geogkey不断重复。到目前为止,我掌握的代码是:

empty <- data.frame(df2$date, df2$impressions)

#creates a new data frame with unique geogkeys
geogname <- unique(data.frame(df1$GEOGKEY))

#create some function that will index each unique geogkey and make a new 
column for df2 with that name (e.g. df2$geogkey <- some function)

new_df <- rbind(empty, df2)
#this should theoretically append all the geogkeys to the dates and 
impressions

我需要为此写一些for循环吗?我被困住了,不知道该怎么办。我也尝试在熊猫身上这样做。你知道吗


Tags: 数据newdatadateframeemptyuniquedf1
1条回答
网友
1楼 · 发布于 2024-05-19 14:43:05

如果我错了,请纠正我,但看起来你是在用“日期”和“印象”的每一个组合重复每一个键。像这样的办法行得通。你知道吗

df <- data.frame()
for(i in unique(df1$GEOKEY){
  for(j in 1:nrow(df2)){

       df <- rbind(df, 
                   data.frame('key' = i, 'date' = df2[j,1], 'impressions' =  df2[j,2]))

   }
}

对于大数据框架来说,这是一个有点麻烦的解决方案。我还假设df2中的行是唯一的。你知道吗

相关问题 更多 >