【问题标题】:Python code to one-liner! Please let me know where's the issue? [closed]Python代码到一行!请让我知道问题出在哪里? [关闭]
【发布时间】:2022-11-29 17:30:37
【问题描述】:

尝试将以下代码放入一个衬里 -

l=[]
for i in df.columns:
    if df[x] == bool:
        l.append(i)
    else:
        continue

还有一些随机的 DataFrame。 工作正常,在这里!

以下是我的尝试 -

l = [x if df[x] == bool else continue for x in df.columns]

#and

l = [x if df[x] == bool for x in df.columns]

这些显示错误!

【问题讨论】:

  • 你能解释一下你的代码吗?您需要布尔列 df.select_dtypes(bool).columns.tolist() 吗?

标签: python python-3.x pandas list one-liner


【解决方案1】:

您此处的代码不完整。 第一部分显示变量 x 的使用。

第二部分一定会产生错误,因为您也将循环变量命名为 x 。例如,尝试将其重命名为 i。 会给出一行:

l = [i if df[x] == bool else continue for i in df.columns]

【讨论】:

  • continue 是否适用于列表理解?
猜你喜欢
  • 1970-01-01
  • 2012-08-13
  • 2020-07-26
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 2015-03-13
  • 2020-03-24
  • 1970-01-01
相关资源
最近更新 更多