方法1. apply
方法配合列表解析:
import pandas as pd
data = {'col_with_lists': [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]}
df = pd.DataFrame(data)
# 使用apply方法和列表解析拆分列
# 将每个列表转换为一个新的Series,分配给新的三列
df[['col1', 'col2', 'col3']] = df['col_with_lists'].apply(pd.Series)
# 删除原始列(可选)
df.drop(columns=['col_with_lists'], inplace=True)
print(df)
方法2. 直接使用列表索引:
# 直接使用列表索引拆分列
df['col1'], df['col2'], df['col3'] = zip(*df['col_with_lists'])
# 删除原始列(可选)
df.drop(columns=['col_with_lists'], inplace=True)
输出:
col1 col2 col3
0 a b c
1 d e f
2 g h i