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

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:

key1key2
0a
0b
0c
1d
1e
1f

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:49:48