解决方案
试试这个:pd.concat + df[col].apply(pd.Series)
# Option-1
pd.concat([df['A'], df['B'].apply(pd.Series).rename(columns={0: 'L1', 1: 'L2'})], axis=1)
# Option-2
# credit: Mark Wang; for suggestion on using, index = ['L1', 'L2']
pd.concat([df['A'], df['B'].apply(pd.Series, index=['L1', 'L2'])], axis=1)
如果您只想保留 L1 和 L2 列
# Option-1
df['B'].apply(pd.Series).rename(columns={0: 'L1', 1: 'L2'})
# Option-2
# credit: Mark Wang; for suggestion on using, index = ['L1', 'L2']
df['B'].apply(pd.Series, index=['L1', 'L2'])
如果要保留所有原始列
# with prefix
pd.concat([df, df['B'].apply(pd.Series).add_prefix(f'B_')], axis=1)
# with user given column-names
pd.concat([df, df['B'].apply(pd.Series).rename(columns={0: 'L1', 1: 'L2'})], axis=1)
逻辑:
- 沿列连接
df 和df_expanded (axis=1)。
- 其中,
df_expanded 是通过执行df[col].apply(pd.Series) 获得的。
这会将列表扩展为列。
- 我添加了一个
.add_prefix('B_') 以明确列的来源(列B)。
示例
df = pd.DataFrame({'A': [1,2,3],
'B': [['11', '12'],
['21', '22'],
['31', '32']]
})
col = 'B'
pd.concat([df, df[col].apply(pd.Series).add_prefix(f'{col}_')], axis=1)