【问题标题】:Pandas - numpy and multiple conditionsPandas - numpy 和多个条件
【发布时间】:2021-12-02 22:35:45
【问题描述】:

我对此还不太了解,但我不知道如何使这项工作:

# Import pandas library
import pandas as pd
import numpy as np
# initialize list of lists
data = [[1, 0], [4, 0], [8, 0]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Value', 'Test'])
df['Test'] = np.where(df['Value'].astype(int) >= 3 & df['Value'].astype(int) <= 7, 1, 2)
# print dataframe.
print(df)

我收到错误:

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

对于此案的任何帮助将不胜感激。它应该做的是根据“值”列中的值的两个条件来更改“测试”列中的值

【问题讨论】:

  • 使用np.where((df['Value'] &gt;= 3) &amp; (df['Value'] &lt;= 7), 1, 2)
  • 这正是我所缺少的——我很傻:(谢谢​​你的回答。

标签: pandas numpy conditional-statements


【解决方案1】:

好的,我缺少括号...应该是这样的:

df['Test'] = np.where((df['Value'].astype(int) >= 3) & (df['Value'].astype(int) <= 7), 1, 2)

【讨论】:

  • 你也可以使用df["Value"].between(3, 7)
猜你喜欢
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 2015-12-11
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
相关资源
最近更新 更多