【Pandas】一行拆多行以及一列拆多列

一行拆多行

原理:1、将值split 为 列表
2、将列表通过 explode 拆分成多行

 code                         final_urls  cnt                                             detail
0  WA0001  https://www.funkernel.com/007    3  4561621743-17609331824-143439967652,4561621743-17609331824-143439967812,4561621743-17609331824-143439967852
1  WA0001  https://www.funkernel.com/008    3  4561621743-17610132869-136953266766,4561621743-17610132869-136953266806,4561621743-17610132869-136953266846
df['value'] = df['value'].map(lambda x: x.split(','))
df = df.explode('value')
 code                         final_urls  cnt                               detail
0  WA0001  https://www.funkernel.com/007    3  4561621743-17609331824-143439967652
0  WA0001  https://www.funkernel.com/007    3  4561621743-17609331824-143439967812
0  WA0001  https://www.funkernel.com/007    3  4561621743-17609331824-143439967852
1  WA0001  https://www.funkernel.com/008    3  4561621743-17610132869-136953266766
1  WA0001  https://www.funkernel.com/008    3  4561621743-17610132869-136953266806
1  WA0001  https://www.funkernel.com/008    3  4561621743-17610132869-136953266846

一列拆多列

根据 “-” 拆分成多列

df[["col1", "col2", "col3"]] = df["value"].str.split('-', 2, expand=True)
   index    code  account_id  campaign_id    adgroup_id                         final_urls
0      0  WA0001  4561621743  17609331824  143439967652  https://www.funkernel.com/007
1      0  WA0001  4561621743  17609331824  143439967812  https://www.funkernel.com/007
2      0  WA0001  4561621743  17609331824  143439967852  https://www.funkernel.com/007
3      1  WA0001  4561621743  17610132869  136953266766  https://www.funkernel.com/008
4      1  WA0001  4561621743  17610132869  136953266806  https://www.funkernel.com/008
5      1  WA0001  4561621743  17610132869  136953266846  https://www.funkernel.com/008

你可能感兴趣的:(python,Pandas,pandas,python)