【问题标题】:Convert a dataframes series with values separated by semicolon to a "1 to 1" dataframe将值以分号分隔的数据帧系列转换为“1 对 1”数据帧
【发布时间】:2021-03-20 02:52:25
【问题描述】:

我真的不知道如何问这个问题,但事情是这样的。我有一个数据框,其中包含以下方式的几列:

Object Propertiy
Apple Red;Round;yummy
Banana Yellow,Large,yummy

我想要一个 DataFrame 的方式如下:

Object Property
Apple Red
Apple Round
Apple Yummy
Banana Yellow
Banana Large
Banana Yummy

你能帮我解决这个问题吗?谢谢

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    试试:

    (1) 用正则表达式(逗号,或分号;|,)分割得到list

    (2) 从列中分解列表

    df["PROPERTIY"] = df["PROPERTIY"].str.split(";|,")
    
    df = df.explode("PROPERTIY").reset_index(drop=True)
    

    输出:

       OBJECT PROPERTIY
    0   Apple       Red
    1   Apple     Round
    2   Apple     yummy
    3  Banana    Yellow
    4  Banana     Large
    5  Banana     yummy
    

    【讨论】:

    • 谢谢,这正是我需要的。最佳
    【解决方案2】:

    假设你的数据框被称为df,你可以使用explode

    df.explode('property')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-24
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      相关资源
      最近更新 更多