为了账号安全,请及时绑定邮箱和手机立即绑定

使用字符值在Pandas中创建新行

使用字符值在Pandas中创建新行

qq_花开花谢_0 2021-03-29 13:27:11
我需要pandas基于特定列中出现的值在数据框中创建新行。创建Split的模式是有一个半冒号,指示我需要在哪里开始新行。dfanimal  cat;dog;catanimal  doganimal  fishcolor   black;greencolor   redwanted_dfanimal  catanimal  doganimal  catanimal  doganimal  fishcolor   blackcolor greencolor   red我见过使用pandas split在df中使用给定字符或值创建新列或行的解决方案(例如here:和here:),但是,我还没有见过使用文本值执行此操作的解决方案。我也看到了能够准确地填充pandas中的空值的解决方案(以及我在此处要求的解决方案)。但是,我需要将这两种技术结合起来,对于单行(或两行)的做法是否可行,我尚不清楚。
查看完整描述

2 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

In [200]: df

Out[200]:

     col1         col2

0  animal  cat;dog;cat

1  animal          dog

2  animal         fish

3   color  black;green

4   color          red


In [201]: (df.set_index('col1')

             .col2.str.split(';', expand=True)

             .stack()

             .reset_index(level=1, drop=True)

             .reset_index(name='col2'))

Out[201]:

     col1   col2

0  animal    cat

1  animal    dog

2  animal    cat

3  animal    dog

4  animal   fish

5   color  black

6   color  green

7   color    red


查看完整回答
反对 回复 2021-04-13
?
慕村225694

TA贡献1880条经验 获得超4个赞

使用numpy.repeat和itertools.chain:


import numpy as np

from itertools import chain


split = df['col2'].str.split(';')


res = pd.DataFrame({'col1': np.repeat(df['col1'], split.map(len)),

                    'col2': list(chain.from_iterable(split))})


print(res)


     col1   col2

0  animal    cat

0  animal    dog

0  animal    cat

1  animal    dog

2  animal   fish

3   color  black

3   color  green

4   color    red


查看完整回答
反对 回复 2021-04-13
  • 2 回答
  • 0 关注
  • 191 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号