You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现CSV多值列拆分:将电影记录按标签展开为多行

How to expand CSV rows with multiple tags into individual tag-movie pairs in Python?

I have a CSV file with movie data where each movie can have multiple tags (space-separated, prefixed with #). Here's a sample of the data (formatted as a table for readability; actual file is a proper CSV):

IDMovietag
1Fury#action #war
2Shrek#cartoon #comedy #fantasy
3Spaceballs#comedy #space
4Cinderfella#comedy
5Galaxy Quest#comedy #space

I want to transform this into a list where each tag gets its own line paired with the movie, like this:

#action Fury
#cartoon Shrek
#comedy Cinderfella
#comedy Galaxy Quest
#comedy Shrek
#comedy Spaceballs
#fantasy Shrek
#space Galaxy Quest
#space Spaceballs
#war Fury

So for 5 movies, I need 10 output lines—one for each tag-movie combination. How can I achieve this in Python?


Here are two straightforward ways to get this done in Python, depending on your preferences for libraries:

Option 1: Use Python's built-in csv module (no extra installs)

If you want to stick to standard libraries without adding any external packages, this approach works perfectly. We'll read the CSV row by row, split the tags into individual entries, then write each tag-movie pair as a separate line:

import csv

# Open input and output files
with open('movies.csv', 'r', newline='') as infile, open('expanded_tags.csv', 'w', newline='') as outfile:
    reader = csv.DictReader(infile)
    # Use space as the delimiter to match your desired output format
    writer = csv.writer(outfile, delimiter=' ')
    
    for row in reader:
        movie = row['Movie']
        # Split the space-separated tag string into a list of individual tags
        tags = row['tag'].split()
        # Write each tag and movie combination to the output
        for tag in tags:
            writer.writerow([tag, movie])

Run this script, and your output file will have exactly the 10 lines you're looking for—each tag paired with its corresponding movie.

Option 2: Use pandas (cleaner syntax for larger datasets)

If you're working with bigger datasets or prefer a more concise workflow, pandas makes this task trivial with its explode() function.

First, install pandas if you haven't already:

pip install pandas

Then use this code:

import pandas as pd

# Load the CSV data into a DataFrame
df = pd.read_csv('movies.csv')

# Split the tag column into a list of tags, then expand each list item into its own row
df['tag'] = df['tag'].str.split()
expanded_df = df.explode('tag')

# Reorder columns to put tag first, then movie
expanded_df = expanded_df[['tag', 'Movie']]

# Save to a space-separated file (no headers or index)
expanded_df.to_csv('expanded_tags.csv', sep=' ', index=False, header=False)

# Or print the result directly to verify
print(expanded_df.to_csv(sep=' ', index=False, header=False))

This will generate exactly the format you specified. The explode() function takes each tag in the list we created and turns it into a separate row, keeping the movie title linked correctly.


内容的提问来源于stack exchange,提问作者James Frick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:17:46