【问题标题】:iterate over list in python using condition and choices使用条件和选择迭代python中的列表
【发布时间】:2019-01-21 06:35:08
【问题描述】:

dataframe

我有这种格式的数据,现在如果以下条件为真,那么我想在类别列中输入一个名称, 如果, 二是没有5, 三是没有 2 或 3 六是没有三,

那么我的类别应该是 fire tv。

我将二、三、六列工具放入列表并压缩并保存在列表4中,

代码:

b=[]
a=[]
for (i,j,k) in list4:
  if (list4[i]==5)& (list4[j]==2|3) & (list4[k]==3):
    print(i,j,k)

【问题讨论】:

标签: python-3.x list pandas dataframe conditional-statements


【解决方案1】:

如果您提供所需的输入和输出,回答会容易得多。但从外观上看,您正在寻找这样的东西:

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'

【讨论】:

  • 因为 Category 列的值为 0,它给出错误 ValueError: Cannot convert non-finite values (NA or inf) to integer,第二、三、六列也是不可迭代的系列
  • 我的错,因为您的 six 列中有 NaN 值,所以您不能总是迭代它们,因此您必须先测试单元格中值的类型。我已经相应地编辑了我的答案。
  • 现在...代码运行没有错误,但类别“消防电视”不存在。实际20列应该有这个标签。
  • 我们在某个地方失踪了......虽然条件是真实的,但我们得到了答案
  • 我没有看到你在twothree列中有列表,我相应地编辑了我的答案。虽然,可能有更聪明的方法来处理three列中的多个条件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 2012-03-19
  • 2021-07-07
  • 2021-05-02
  • 2015-08-11
  • 2017-11-29
  • 2014-09-16
相关资源
最近更新 更多