我正在尝试根据来自同一行中其他单元格的信息,在每行具有唯一值的食品成分数据框中创建一个新列。
该表基本上如下所示:
ingredient_name | ingredient_method | consolidated_name
Cheese | [camembert, pkg] |
Cheese | [cream, pastueri] |
Egg | [raw, scrambled] |
我正在尝试遍历行并consolidated_name
使用来自ingredient_name
或 的值填充列ingredient_method
。
例如,如果ingredient_name
是“奶酪”,我希望该行的合并名称是ingredient_method
.
这是我到目前为止的代码:
for i, row in df.iterrows():
consolidated = df['ingredient_name']
if (df['ingredient_name'] == 'Cheese').all():
consolidated = df['ingredient_method'][0]
df.set_value(i,'consolidated_name',consolidated)
代码运行没有错误,但数据帧中的任何值都没有变化。
有任何想法吗?
您可以DataFrame.apply
为此目的使用。只需将您的决策逻辑(现在处于for
循环中)包装到相应的函数中。
def func(row):
if row['ingredient_name'] == 'Cheese':
return row['ingredient_method'][0]
return None
df['consolidated_name'] = df.apply(func, axis=1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句