python - 如何在“Array”类型的 python pandas 数据框列中检查 AND 和 OR 条件?
问题描述
我创建了一个函数来检查熊猫数据框的数组列中的每个值,然后将值相应地分配给新列。基本上根据食物摄入量预测饮食是否健康。
我写的功能:
创建一个名为“diet_status”的新列,并根据数组类型的“food_intake”列中的值分配值。
def diet(a):
if 'fruits' in a:
y = 'healthy'
elif 'vegetables' in a:
y = 'healthy'
elif 'chips' in a:
y = 'unhealthy'
elif 'sweets' in a:
y = 'unhealthy'
else
y = 'NA'
return y
df["diet_status"] = df["food_intake"].apply(diet)
如何在这里检查多个条件?例如,如果“food_intake”数组包含“(fruits AND vegetables) AND (chips OR sweets)”,我想将其命名为“balanced”。基本上需要检查数组中值的 AND/OR 条件。谁能帮我解决这个问题。
解决方案
因为在这里使用标量是必要的使用or
and and
, not|
和 not &
:
def diet(a):
m1 = ('fruits' in a) or ('vegetables' in a)
m2 = ('chips' in a) or ('sweets' in a)
if m1:
y = 'healthy'
elif m2:
y = 'unhealthy'
elif m1 and m2:
y = 'balanced'
else
y = 'NA'
return y
推荐阅读
- android - 使用深色主题时,MaterialDatePicker 和 TimePickerDialog 的样式不同
- python - Python pandas:获取组的第一个值
- ruby-on-rails - 为什么 RailsAdmin 加载我的编辑视图这么慢?
- continuous-integration - 如何在 Gitlab 上运行的 CI 作业中仅重试失败的测试?
- amazon-web-services - AWS API Gateway - 为 CloudWatch Log 启用 $input
- swift - Swift ui macos @Published nil 或 Int
- python - 根据给定的索引对列表连接二维数组行的有效方法
- python - Pandas read_csv 不读取文件(while 循环)
- xamarin - 使用动态数据将 IObservable 转换为 SourceCache
- excel - 使用计时器增加单元格值