【问题标题】:How to split and duplicate rows according to string in one column with python / pandas?python - 如何使用python / pandas根据一列中的字符串拆分和复制行?
【发布时间】:2019-05-04 18:08:27
【问题描述】:

我有一个 df,其中一些值被添加到同一行,就像这个假 df:

    [['Apple, Kiwi, Clementine', np.nan , 'Cycling', 5], 
     ['Kiwi', 'Blue',  np.nan , 20], 
     ['Banana, Clementine',  np.nan , 'Hockey', 12], 
     ['Apple', 'Purple', 'Triathlon', 15], 
     ['Kiwi',  np.nan, 'Swimming', 8]]), 
                     columns=['fruit', 'colour', 'sport', 'wins'])

我想要的是复制具有多个水果的行,同时将第一个条目拆分为仅包含一个水果。 最后,我想绘制每个水果的平均胜数。因此,如果有一种分组方式,其中提到的每个水果都与正确的水果分组,可以这么说也可以。

我尝试了一些字符串操作,但随后它被简单地拆分,并且其他列中的值没有重复。 这很令人沮丧,因为我知道如何在 r 中做到这一点,但我是 python 的初学者。

【问题讨论】:

    标签: python string pandas


    【解决方案1】:

    使用here@Wen-Ben 的解决方案:

    s=pd.DataFrame([[x] + [z] for x, y in zip(df.index,df.fruit.str.split(',')) for z in y],
                   columns=[0,'Fruit'])
    df_new=s.merge(df,left_on=0,right_index=True).drop(0,1)
    print(df_new)
    

             Fruit                    fruit  colour      sport  wins
    0        Apple  Apple, Kiwi, Clementine     NaN    Cycling     5
    1         Kiwi  Apple, Kiwi, Clementine     NaN    Cycling     5
    2   Clementine  Apple, Kiwi, Clementine     NaN    Cycling     5
    3         Kiwi                     Kiwi    Blue        NaN    20
    4       Banana       Banana, Clementine     NaN     Hockey    12
    5   Clementine       Banana, Clementine     NaN     Hockey    12
    6        Apple                    Apple  Purple  Triathlon    15
    7         Kiwi                     Kiwi     NaN   Swimming     8
    

    注意如果需要,您可以选择删除fruit 列。

    【讨论】:

    • 太棒了!现在清理不同的拼写等会容易得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2020-10-17
    相关资源
    最近更新 更多