在数据框中如何将带有列表的列(所有行的长度相同)分解为同一行的不同列
At a dataframe how to explode a column with a list (with same length at all rows) into different columns at the same row
我有以下数据框:
df=pd.DataFrame({'A': ['1','2', '3'], 'List': [['a1','a2'], ['b1','b2'], ['c1','c2']]})
Out[18]:
A List
0 1 [a1, a2]
1 2 [b1, b2]
2 3 [c1, c2]
我想将 List 列分解为两个新列(L1 和 L2) 在同一行。
A L1 L2
0 1 a1 a2
1 2 b1 b2
2 3 c1 c2
哪种方法最快?
最好同时为列分配名称(L1 和 L2)。
提前致谢并致以最诚挚的问候,
巴勃罗 G
解决方案
试试这个: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)
逻辑:
- 沿着列 (
axis=1
) 连接 df
和 df_expanded
。
- 其中,
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)
尝试:
df[['A']].join(df['List'].apply(pd.Series, index=['L1', 'L2']))
我有以下数据框:
df=pd.DataFrame({'A': ['1','2', '3'], 'List': [['a1','a2'], ['b1','b2'], ['c1','c2']]})
Out[18]:
A List
0 1 [a1, a2]
1 2 [b1, b2]
2 3 [c1, c2]
我想将 List 列分解为两个新列(L1 和 L2) 在同一行。
A L1 L2
0 1 a1 a2
1 2 b1 b2
2 3 c1 c2
哪种方法最快?
最好同时为列分配名称(L1 和 L2)。
提前致谢并致以最诚挚的问候,
巴勃罗 G
解决方案
试试这个: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)
逻辑:
- 沿着列 (
axis=1
) 连接df
和df_expanded
。 - 其中,
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)
尝试:
df[['A']].join(df['List'].apply(pd.Series, index=['L1', 'L2']))