【问题标题】:The truth value of a Series is ambiguous (if)Series 的真值不明确(如果)
【发布时间】:2023-01-08 03:51:14
【问题描述】:

当我想添加新列时,if 语句出现问题。

import pandas as pd
scan = pd.DataFrame([[1,2,3],['a','b','c']], columns=['st','nd','rd'])
scan['th'] = 0 if scan['st'] == 0 else 1

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我怎样才能解决这个问题?

【问题讨论】:

标签: python pandas series


【解决方案1】:

使用 numpy.where 将这些条件和值应用于整个数组:

scan['th'] = np.where(scan['st'] == 0, 0, 1)

将前一种方法与这种方法进行基准测试可能会很有趣:

scan['th'] = (scan['st'] != 0).astype(int)

【讨论】:

  • Series.where不是只能做原地作业吗?这里 OP 从“st”创建一个新的“th”列,而不是替换“st”的内容。
猜你喜欢
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 2019-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
相关资源
最近更新 更多