在创建新列之前,合并列并对值进行排序

2024-06-02 08:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个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'])

我希望有人能指点我一个简单的解决办法来完成这一点。我在这个论坛上看了很多帖子,但就是不知道怎么做。你知道吗

我试图将这些行转换成一个列表,然后对列表进行排序,最后将列表打印为新行。我没有成功的方法,并开始认为我这样做是艰难的,这就是为什么我现在要求别人的帮助。非常感谢。你知道吗


Tags: csv数据pandasdf列表排序summarysugar
2条回答

读取数据帧-

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')
def sort_ingredients(row):
    return ';'.join(row.sort_values().tolist())

df['Ingredient Summary'] = df.apply(sort_ingredients, axis=1)

相关问题 更多 >