Python 3.x 使用条件和选项在python中迭代列表
我有这种格式的数据,现在如果下面的条件为真,那么我想在类别列中输入一个名称, 如果 二是没有五,, 三是没有2或3 六是没有三 那么我的分类应该是消防电视 我把二、三、六列工具放到列表中,压缩并保存在列表4中 代码:Python 3.x 使用条件和选项在python中迭代列表,python-3.x,list,pandas,dataframe,conditional-statements,Python 3.x,List,Pandas,Dataframe,Conditional Statements,我有这种格式的数据,现在如果下面的条件为真,那么我想在类别列中输入一个名称, 如果 二是没有五,, 三是没有2或3 六是没有三 那么我的分类应该是消防电视 我把二、三、六列工具放到列表中,压缩并保存在列表4中 代码: 如果您提供了所需的输入和输出,那么回答会容易得多。但从表面上看,你正在寻找这样的东西: mask = (df.two.apply(lambda x: 5 in x if type(x)=='list' else x == 5) | \ (df.three.apply
如果您提供了所需的输入和输出,那么回答会容易得多。但从表面上看,你正在寻找这样的东西:
mask = (df.two.apply(lambda x: 5 in x if type(x)=='list' else x == 5) | \
(df.three.apply(lambda x: 2 in x if type(x)=='list' else x == 2) | \
(df.three.apply(lambda x: 3 in x if type(x)=='list' else x == 3) | \
(df.six.apply(lambda x: 3 in x if type(x)=='list' else x == 3))
df['category'] = np.nan
df.loc[mask,'category'] = 'fire tv'
欢迎来到SO。请提供一个,即没有图像/链接,只有文本。由于类别列的值为0,其给定的错误值错误:无法将非有限值(NA或inf)转换为整数,而且第二、三、六列的类型为系列,这不是很糟糕,因为您的
six
列中有NaN
值,因此您不能总是迭代它们,因此,您必须首先测试单元格中值的类型。我已经相应地编辑了我的答案。现在…代码正在运行,没有错误,但“消防电视”类别中没有。实际上,20列中应该有这个标签。我们遗漏了一些地方…虽然条件是真的,但我们得到的是ansI。没有看到您在2列和3列中也有列表,我相应地编辑了我的答案。尽管如此,可能有一种更聪明的方法来处理列three
mask = (df.two.apply(lambda x: 5 in x if type(x)=='list' else x == 5) | \
(df.three.apply(lambda x: 2 in x if type(x)=='list' else x == 2) | \
(df.three.apply(lambda x: 3 in x if type(x)=='list' else x == 3) | \
(df.six.apply(lambda x: 3 in x if type(x)=='list' else x == 3))
df['category'] = np.nan
df.loc[mask,'category'] = 'fire tv'