【问题标题】:Rearrange values in a Pandas DF Cell by some separated value value in alphabetical order按字母顺序按某些分隔值重新排列 Pandas DF 单元中的值
【发布时间】:2022-01-26 14:32:33
【问题描述】:

我有以下df:

      ID    Foods
0   100 Apple
1   101 Apple | Orange | Grape
2   102 Apples & Peanut Butter | Peanuts | Coffee
3   103 Grapes and Apples | Melon | Butter
4   104 Milk, Cookies | Cake | Cupcake

我想按字母顺序组织每个单元格,以| 分隔,因此结果将是:

        ID     Foods
    0   100 Apple
    1   101 Apple | Grape | Orange
    2   102 Apples & Peanut Butter | Coffee | Peanuts
    3   103 Butter | Grapes and Apples | Melon
    4   104 Cake | Cupcake | Milk, Cookies 

样本df:

df = {
 'ID': {0: '100', 1: '101', 2: '102', 3: '103', 4: '104'},
 'Foods': {0: 'Apple',
  1: 'Apple | Orange | Grape',
  2: 'Apples & Peanut Butter | Peanuts | Coffee ',
  3: 'Grapes and Apples | Melon | Butter',
  4: 'Milk, Cookies | Cake | Cupcake'}}

pd.DataFrame.from_dict(x)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    将食物列拆分成一个列表

    df['Foods'] = df.Foods.str.split('\s*|\s*')
    

    展开列表,对值进行排序并恢复到旧格式

    df
    .explode('Foods')
    .sort_values(by=['Foods'], ascending=True)
    .groupby('ID')
    .agg(' | '.join)
    

    【讨论】:

      【解决方案2】:

      只需使用.str.split 按|(+ 和空格,左或右)拆分,在每个拆分列表上调用sorted(返回一个新的排序列表),然后将它们重新连接在一起:

      df['Foods'] = df['Foods'].str.split('\s*\|\s*').apply(sorted).str.join(' | ')
      

      输出:

      >>> df
          ID                                       Foods
      0  100                                       Apple
      1  101                      Apple | Grape | Orange
      2  102  Apples & Peanut Butter | Coffee  | Peanuts
      3  103          Butter | Grapes and Apples | Melon
      4  104              Cake | Cupcake | Milk, Cookies
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-23
        • 1970-01-01
        • 2022-01-25
        相关资源
        最近更新 更多