Pandas中如何将含多值的列拆分并展开为对应原索引的多行?
Sure thing! This is a common task in Pandas, and there's a super straightforward way to do it using str.split() combined with explode(). Here's how:
First, let's recreate your original DataFrame:
import pandas as pd df = pd.DataFrame({ 'key1': [0, 1], 'key2': ['a, b, c', 'd, e, f'] })
Then, split the comma-separated values in key2 into a list, and use explode() to expand each list element into its own row while keeping the corresponding key1 value:
# Split the key2 column into lists df['key2'] = df['key2'].str.split(', ') # Explode the list into individual rows expanded_df = df.explode('key2')
You can even condense this into a single line for brevity:
expanded_df = df.assign(key2=df['key2'].str.split(', ')).explode('key2')
The resulting expanded_df will match exactly what you're looking for:
| key1 | key2 |
|---|---|
| 0 | a |
| 0 | b |
| 0 | c |
| 1 | d |
| 1 | e |
| 1 | f |
If your key2 values have inconsistent spacing (like sometimes just commas without spaces), you can adjust the split to handle that by splitting on commas first then stripping whitespace from each item:
df['key2'] = df['key2'].str.split(',').apply(lambda x: [item.strip() for item in x])
That should cover all edge cases for this task!
内容的提问来源于stack exchange,提问作者xman

