gpt4 book ai didi

python - Pandas 数据帧 : Pipe separated values in a cell

转载 作者:行者123 更新时间:2023-11-30 22:43:00 25 4
gpt4 key购买 nike

我有一个如下所示的数据框:

from      to         cc      extra columns
-------------------------------------------
1 2 3 sth
1|1 4 sth
3 1|2 4|5 sth

我想要一个新的数据框,为每个管道分隔值创建一个新行,如下所示:

from       to        cc       extra columns
--------------------------------------------
1 2 3 sth
1 4 sth
1 4 sth
3 1 4 sth
3 2 4 sth
3 1 5 sth
3 2 5 sth

有人可以帮我解决这个问题吗?

谢谢!

最佳答案

一个不优雅但可行的解决方案:

import pandas as pd
import itertools

df = pd.read_csv('path/to/file.csv', index_col=None)

all_rows = []
for _, r in df.iterrows():

froms = str(r['from']).split('|')
to = str(r['to']).split('|')
ccs = str(r['cc']).split('|')

rows = [[f, t, cc] + list(r[df.columns[3:]]) for f, t, cc in itertools.product(froms, to, ccs)]
all_rows += rows

df_2 = pd.DataFrame(data=all_rows, columns=df.columns)

关于python - Pandas 数据帧 : Pipe separated values in a cell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41927973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com