Skip to main content
 首页 » 编程设计

python之Pandas groupby 和文件写入问题

2025年05月04日15davidwang456

我有一些将数据写入文件的 pandas groupby 函数,但由于某种原因,我将冗余数据写入文件。这是代码:

此函数应用于数据框中的每个项目

def item_grouper(df): 
    # Get the frequency of each tag applied to the item 
    tag_counts = df['tag'].value_counts()  
    # Get the most frequent tag (or tags, assuming a tie) 
    max_tags = tag_counts[tag_counts==tag_counts.max()] 
    # Get the total nummber of annotations for the item 
    total_anno = len(df) 
    # Now, process each user who tagged the item 
    return df.groupby('uid').apply(user_grouper,total_anno,max_tags,tag_counts) 
 
# This function gets applied to each user who tagged an item 
def user_grouper(df,total_anno,max_tags,tag_counts): 
    # subtract user's annoations from total annoations for the item 
    total_anno = total_anno - len(df) 
    # calculate weight 
    weight = np.log10(total_anno) 
    # check if user has used (one of) the top tag(s), and adjust max_tag_count 
    if len(np.intersect1d(max_tags.index.values,df['iid']))>0: 
        max_tag_count = float(max_tags[0]-1) 
    else: 
        max_tag_count = float(max_tags[0]) 
    # for each annotation... 
    for i,row in df.iterrows(): 
        # calculate raw score 
        raw_score = (tag_counts[row['tag']]-1) / max_tag_count 
        # write to file 
        out.write('\t'.join(map(str,[row['uid'],row['iid'],row['tag'],raw_score,weight]))+'\n') 
    return df 

因此,一个分组函数按 iid(item id)对数据进行分组,进行一些处理,然后按 uid(user_id)对每个子数据帧进行分组,进行一些计算,然后写入输出文件。现在,输出文件应该在原始数据框中每行只有一行,但事实并非如此!我不断将相同的数据多次写入文件。例如,如果我运行:

out = open('data/test','w') 
df.head(1000).groupby('iid').apply(item_grouper) 
out.close() 

输出应该有 1000 行(代码在数据框中每行只写一行),但结果输出文件有 1,997 行。查看文件显示完全相同的行被多次(2-4)次写入,似乎是随机的(即并非所有行都是双写的)。知道我在这里做错了什么吗?

请您参考如下方法:

参见 docs在申请。 Pandas 将在第一组调用该函数两次(以确定快/慢代码路径),因此函数 (IO) 的副作用将在第一组发生两次。

这里最好的选择可能是直接遍历组,如下所示:

for group_name, group_df in df.head(1000).groupby('iid'): 
    item_grouper(group_df)