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

我需要pandas基于特定列中出现的值在数据框中创建新行。


创建Split的模式是有一个半冒号,指示我需要在哪里开始新行。


df


animal  cat;dog;cat

animal  dog

animal  fish

color   black;green

color   red

wanted_df


animal  cat

animal  dog

animal  cat

animal  dog

animal  fish

color   black

color green

color   red

我见过使用pandas split在df中使用给定字符或值创建新列或行的解决方案(例如here:和here:),但是,我还没有见过使用文本值执行此操作的解决方案。我也看到了能够准确地填充pandas中的空值的解决方案(以及我在此处要求的解决方案)。但是,我需要将这两种技术结合起来,对于单行(或两行)的做法是否可行,我尚不清楚。


qq_花开花谢_0
浏览 192回答 2
2回答

UYOU

In [200]: dfOut[200]:     col1         col20  animal  cat;dog;cat1  animal          dog2  animal         fish3   color  black;green4   color          redIn [201]: (df.set_index('col1')             .col2.str.split(';', expand=True)             .stack()             .reset_index(level=1, drop=True)             .reset_index(name='col2'))Out[201]:     col1   col20  animal    cat1  animal    dog2  animal    cat3  animal    dog4  animal   fish5   color  black6   color  green7   color    red

慕村225694

使用numpy.repeat和itertools.chain:import numpy as npfrom itertools import chainsplit = df['col2'].str.split(';')res = pd.DataFrame({'col1': np.repeat(df['col1'], split.map(len)),                    'col2': list(chain.from_iterable(split))})print(res)     col1   col20  animal    cat0  animal    dog0  animal    cat1  animal    dog2  animal   fish3   color  black3   color  green4   color    red
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python