代码之家  ›  专栏  ›  技术社区  ›  owwoow14

使用字符值在熊猫中创建新行

  •  1
  • owwoow14  · 技术社区  · 6 年前

    我需要在 pandas 基于特定列中出现的值的数据帧。

    创建拆分的模式是,有一个分号指示我需要在哪里启动新行。

    东风

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

    德西雷德

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

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

    2 回复  |  直到 6 年前
        1
  •  1
  •   MaxU - stand with Ukraine    6 年前
    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
    
        2
  •  0
  •   jpp    6 年前

    使用 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