基于 pandas 数据框中的列标签的条件操作

Conditional operation based on column label in pandas dataframe

我下面有一个数据框

df=pd.DataFrame(np.random.randn(6,3),index=list("ABCDEF"),columns=list("XYZ"))
df.reset_index(inplace=True)
df

我想要一个名为 "Q" 的新列。 "Q"列下的值是根据索引列下的标签计算的,满足以下三个条件:

conditions=[(df["index"]== "A"|"B"|"C"|"D"),(df["index"]== "E"),(df["index"]== "F")]
returned_value=[df["X"]+df["Y"],df["Y"]*2,df["Z"]]

所以我在考虑使用

df["Q"]=np.select(conditions, returned_value)

但是我在定义条件后得到了错误。我先用or,又报错,然后改成|,却报如下。关于如何实现我想要的任何提示?

TypeError: unsupported operand type(s) for |: 'str' and 'str'

使用 isin 检查多个值的成员资格:

np.random.seed(1213)
df=pd.DataFrame(np.random.randn(6,3),index=list("ABCDEF"),columns=list("XYZ"))
df.reset_index(inplace=True)

conditions=[df["index"].isin(["A","B","C","D"]),(df["index"]== "E"),(df["index"]== "F")]
returned_value=[df["X"]+df["Y"],df["Y"]*2,df["Z"]]
df["Q"]=np.select(conditions, returned_value)
print (df)
  index         X         Y         Z         Q
0     A  0.511604 -0.217660 -0.521060  0.293943
1     B  1.253270  1.104554 -0.770309  2.357825
2     C  0.632975 -1.322322 -0.936332 -0.689347
3     D  0.436361  1.233744  0.527565  1.670105
4     E -0.369576  1.820059 -1.373630  3.640118
5     F -0.414554 -0.098443  0.904791  0.904791

但不需要重新设置索引,然后检查df.index:

np.random.seed(1213)
df=pd.DataFrame(np.random.randn(6,3),index=list("ABCDEF"),columns=list("XYZ"))

conditions=[df.index.isin(["A","B","C","D"]),(df.index == "E"),(df.index== "F")]
returned_value=[df["X"]+df["Y"],df["Y"]*2,df["Z"]]
df["Q"]=np.select(conditions, returned_value)
print (df)
          X         Y         Z         Q
A  0.511604 -0.217660 -0.521060  0.293943
B  1.253270  1.104554 -0.770309  2.357825
C  0.632975 -1.322322 -0.936332 -0.689347
D  0.436361  1.233744  0.527565  1.670105
E -0.369576  1.820059 -1.373630  3.640118
F -0.414554 -0.098443  0.904791  0.904791