【问题标题】:How do I create a new pandas dataframe column with the contents of another, but only if the other column meets a condition?如何使用另一个列的内容创建一个新的 pandas 数据框列,但前提是另一列满足条件?
【发布时间】:2021-08-09 15:41:54
【问题描述】:

我有这行代码:

df['new_column']=df['price'][df['bathrooms']>=2 and df['bathrooms']<3]

基本上,我想创建一个包含列表价格的新列(来自列价格),但前提是浴室列包含大于或等于 2 但小于 3 的值。我收到了错误

Series 的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

如何更正此代码?

谢谢!

【问题讨论】:

标签: python-3.x pandas dataframe boolean-logic


【解决方案1】:

您需要适当的 parathensis,you cannot use 'and' use ampsand (&) instead 并改用 loc,尝试:

df['new_column']=df.loc[(df['bathrooms']>=2) & (df['bathrooms']<3), 'price']

【讨论】:

    【解决方案2】:

    你可以使用这个:query in pandas

    df1 =df.query('bathrooms>=2 and bathrooms<3')
    df1[['price']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 2021-07-07
      相关资源
      最近更新 更多