Python实现CSV多值列拆分:将电影记录按标签展开为多行
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):
| ID | Movie | tag |
|---|---|---|
| 1 | Fury | #action #war |
| 2 | Shrek | #cartoon #comedy #fantasy |
| 3 | Spaceballs | #comedy #space |
| 4 | Cinderfella | #comedy |
| 5 | Galaxy 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

