熊猫用 min 函数填充列值

时间:2021-07-28 20:25:23

标签: python pandas min

我有一个包含 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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

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

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