【问题标题】:pandas fill the column values with min function熊猫用 min 函数填充列值
【发布时间】:2021-10-04 13:56:42
【问题描述】:

我有一个包含 2 列的数据框,我需要添加第三列“开始”。但是我的代码由于某种原因不起作用,我不知道为什么。这是我的代码

df.loc[df.type=='C', 'start']= min(-1+df['dq']-3,4)
df.loc[df.type=='A', 'start']= min(-3+df['dq']-3,4)
df.loc[df.type=='B', 'start']= min(-3+df['dq']-5,4)

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), 
a.any() or a.all().

数据集如下所示:

type        dq
A            3
A            4
B            8
C            3

【问题讨论】:

  • 预期输出是什么?

标签: python pandas min


【解决方案1】:

由于您传递给min() 的第一个参数是一个系列,而第二个 (4) 是一个int,因此引发了错误。

由于您使用 min 将大于 4 的值替换为 4,因此您可以在最后使用 where 替换一次:

df.loc[df.type=='C', 'start'] = -1+df['dq']-3
df.loc[df.type=='A', 'start'] = -3+df['dq']-3
df.loc[df.type=='B', 'start'] = -3+df['dq']-5
df["start"] = df["start"].where(df["start"]<4,other=4)

>>> df
  type  dq  start
0    A   3     -3
1    A   4     -2
2    B   8      0
3    C   3     -1

获取专栏的另一种(可能更简洁)方法是使用numpy.select,如下所示:

import numpy as np

df["start"] = np.select([df["type"]=="A", df["type"]=="B", df["type"]=="C"],
                        [df['dq']-6, df["dq"]-8, df["dq"]-4])
df["start"] = df["start"].where(df["start"]<4, 4)

【讨论】:

    【解决方案2】:

    您不能使用带最小值的系列。相反,您可以这样做:

    s = (df['dq'] - df['type'].map({'A': 6, 'B': 8, 'C': 4}))
    df['start'] = s.where(s<4, 4)
    

    输出:

      type  dq  start
    0    A   3     -3
    1    A   4     -2
    2    B   8      0
    3    C   3     -1
    

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 2018-07-02
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多