【问题标题】:Combine columns and sort the values before creating a new column在创建新列之前合并列并对值进行排序
【发布时间】:2018-06-13 19:46:00
【问题描述】:

我正在制作一个 python 脚本,我想在创建新列之前组合几列字符串数据并按字母顺序对它们进行排序。为了简化我的示例,这里是我正在处理的数据格式的一个非常简单的示例:

Ingredient 1, Ingredient 2, Ingredient 3
pickles, beef, mayo
sugar, flour, eggs

我想要实现的最终产品是一个新列,其中 3 种成分被组合并按字母顺序排列:

Ingredient 1, Ingredient 2, Ingredient 3, Ingredient Summary
pickles, beef, mayo, beef; mayo; pickles 
sugar, flour, eggs, eggs; flour; sugar

大约两周前,我刚开始学习 python,目的是从网站上抓取一些数据并将其组织成 csv,以便在 excel 中进行操作。我已经成功地从网站上抓取数据,但我真的很难修改 CSV 数据。这是我目前的代码,你可以看到代码目前没有排序,我只能弄清楚如何将数据组合到一个新列中。

import pandas

CSV_file = pandas.read_csv('ingredients.csv')
df = pandas.DataFram(CSV_file)

df['Ingredient Summary'] = df['Ingredient 1'] + '; ' + df['Ingredient 2']
print(df['Ingredient Summary'])

我希望有人可以为我指出一个简单的解决方案来完成此任务。我在这个论坛上看了很多帖子,但就是不知道怎么做。

我试图将行转换为列表,然后对列表进行排序,最后将列表打印为新行。我在这种方法上没有成功,并且开始认为我这样做很艰难,这就是为什么我现在寻求其他人的帮助。谢谢你。

【问题讨论】:

    标签: python pandas csv sorting


    【解决方案1】:

    阅读您的数据框 -

    df = pd.read_csv('file.csv', sep=',\s*', engine='python')
    df
    
      Ingredient 1 Ingredient 2 Ingredient 3
    0      pickles         beef         mayo
    1        sugar        flour         eggs
    

    调用np.sort,将结果加载到Series,然后调用.str.join -

    df['Summary'] = pd.Series(np.sort(df.values, axis=1).tolist()).str.join('; ')
    df
    
    0    beef; mayo; pickles
    1     eggs; flour; sugar
    dtype: object
    

    使用to_csv 再次保存到 CSV -

    df.to_csv('file.csv')
    

    【讨论】:

    • 直到现在我才能试用您的解决方案。它完全按照我的意愿工作。非常感谢您花时间回复您,您为我节省了很多额外的挫败感。我为你的答案投了票,但由于我的名声太低,它还不让我算。
    • @Marcel 感谢您的接受。如果您喜欢答案,您也可以投票:)
    【解决方案2】:
    def sort_ingredients(row):
        return ';'.join(row.sort_values().tolist())
    
    df['Ingredient Summary'] = df.apply(sort_ingredients, axis=1)
    

    【讨论】:

    • 假设您的意思是 sort_values 而不是排序值,这仍然比调用 np.sort 慢。如果可以,请始终避免使用apply
    • 非常感谢您的回复。我最终使用了np.sort 的另一个答案,因为关于sort_values 的评论变慢了。
    猜你喜欢
    • 1970-01-01
    • 2018-08-19
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 2021-08-23
    • 1970-01-01
    相关资源
    最近更新 更多