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

2024-06-17 13:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在这里我需要创建一个新的分号模式。在

测向

animal  cat;dog;cat
animal  dog
animal  fish
color   black;green
color   red

期望值

^{pr2}$

我见过使用pandas split来使用df中的给定字符或值(例如here:和here:)创建新列或行的解决方案,但是,我还没有看到使用文本值来实现这一点的解决方案。我还看到了能够准确填充pandas中的空值的解决方案(以及我自己要求的解决方案here)。但是,我需要将这两种技术结合起来,我不清楚这是否可以在一行代码(或两行代码)中实现。在


Tags: 数据代码pandashere模式greenred解决方案
2条回答

使用numpy.repeatitertools.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
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

相关问题 更多 >