pandas如何替换整列数据(如何将Dataframe单元格中的列表拆分为Pandas中的行)

pandas如何替换整列数据(如何将Dataframe单元格中的列表拆分为Pandas中的行)(1)

给定的烹饪数据集由三列组成。最后一列是成分列表。

pandas如何替换整列数据(如何将Dataframe单元格中的列表拆分为Pandas中的行)(2)

我想计算一种配料在每种菜肴中的使用频率以及使用该配料的菜肴的数量。我不得不在最后一列中拆分列表并将其值用作行。此外,我必须在每一行添加正确的美食。

我们来看一个例子。如果我的数据集看起来像这样:

cuisine_1,id_1,[ingredient_1, ingredient_2, ingredient_3]

cuisine_2,id_2,[ingredient_4, ingredient_5]

我想要输出:

cuisine_1,id_1,ingredient_1

cuisine_1,id_1,ingredient_2

cuisine_1,id_1,ingredient_3

cuisine_2,id_2,ingredient_4

cuisine_2,id_2,ingredient_5

我写了一些Python代码,这些代码可以完成工作并正常工作,但看起来不像Pandas代码。看这里,我仔细分析了数据框架并重新构建了它。

ingredients = []

cuisines = []

ids = []

for _, row in data.iterrows():

cuisine = row.cuisine

identifier = row.id

for ingredient in row.ingredients:

cuisines.append(cuisine)

ingredients.append(ingredient)

ids.append(identifier)

ingredient_to_cuisine = pd.DataFrame({

"id": ids,

"ingredient": ingredients,

"cuisine": cuisines

})

更好的方法

首先,我们必须将elements列(包含一个值列表)拆分为新的列。这很容易做到,而且输出保存了索引。看看Python代码:

data.ingredients.apply(pd.Series)

pandas如何替换整列数据(如何将Dataframe单元格中的列表拆分为Pandas中的行)(3)

为了测试,我将数据集限制为三行

现在,我们可以将列与其他数据集合并。有很多空值,但这是可以的。稍后我们将处理这些问题。Python实现如下:

data.ingredients.apply(pd.Series) \

.merge(data, left_index = True, right_index = True)

pandas如何替换整列数据(如何将Dataframe单元格中的列表拆分为Pandas中的行)(4)

首先,我不再需要旧的成分列了。所以,让我们放弃它。Python代码如下:

data.ingredients.apply(pd.Series) \

.merge(data, right_index = True, left_index = True) \

.drop(["ingredients"], axis = 1)

pandas如何替换整列数据(如何将Dataframe单元格中的列表拆分为Pandas中的行)(5)

现在,我们可以使用melt函数将数字列转换为单独的行。注意,我使用cuisine和id作为标识变量。

data.ingredients.apply(pd.Series) \

.merge(data, right_index = True, left_index = True) \

.drop(["ingredients"], axis = 1) \

.melt(id_vars = ['cuisine', 'id'], value_name = "ingredient")

pandas如何替换整列数据(如何将Dataframe单元格中的列表拆分为Pandas中的行)(6)

看起来“variable”列没用,因此我们也可以删除它。Python实现如下:

data.ingredients.apply(pd.Series) \

.merge(data, right_index = True, left_index = True) \

.drop(["ingredients"], axis = 1) \

.melt(id_vars = ['cuisine', 'id'], value_name = "ingredient") \

.drop("variable", axis = 1)

pandas如何替换整列数据(如何将Dataframe单元格中的列表拆分为Pandas中的行)(7)

我告诉过你们,我们会去掉空值。现在,是时候做了。

data.ingredients.apply(pd.Series) \

.merge(data, right_index = True, left_index = True) \

.drop(["ingredients"], axis = 1) \

.melt(id_vars = ['cuisine', 'id'], value_name = "ingredient") \

.drop("variable", axis = 1) \

.dropna()

pandas如何替换整列数据(如何将Dataframe单元格中的列表拆分为Pandas中的行)(8)

完成!现在我们有一个数据集,其中的成分分别在不同的行中。

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页