Pandas,Multiple Case Statement,ValueError:应该同时给出x和y或两者都不给出

2024-10-03 21:36:38 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试在我的代码中合并以下case语句。你知道吗

d1['newcol'] = np.where((d1['business_name'] == 'HELP')&(d1['level'] == 'Component'), d1['component'], np.where((d1['business_name'] == 'HELP')&(d1['level'] == 'Package'),d1['package'], np.where(d1['business_name'] == 'PHELPS',d1['reporting']))) 

或者案例伪代码看起来像:

   newcol=case WHEN ((business_name = 'HELP' AND level = 'Component')) THEN component WHEN ((business_name = 'HELP' AND level = 'Package')) THEN package WHEN (business_name = 'PHELS') THEN reporting END

我得到的错误是:

ValueError: either both or neither of x and y should be given

任何帮助都将不胜感激。你知道吗


Tags: 代码namepackagenphelpbusinesswherelevel
2条回答

这里有一个方法可以实现这个结果。使用其他样本数据。你知道吗

import pandas as pd
import numpy as np
from io import StringIO

# Sample data
df = pd.read_csv(StringIO(
"""a,b
1,1
1,2
2,1
2,2"""))

# Create new column using conditional indexing
df["c"] = ""
df.loc[df["a"] == 1, "c"] = "one something"
df.loc[(df["a"] == 2) & (df["b"] == 1), "c"] = "two one"
df.loc[(df["a"] == 2) & (df["b"] != 1), "c"] = "two something"
df

# Out[29]: 
#    a  b              c
# 0  1  1  one something
# 1  1  2  one something
# 2  2  1        two one
# 3  2  2  two something

您可能希望在数据帧的所有行上应用lambda函数。你知道吗

df['newcol'] = df.apply(lambda row: 
                        row['component'] if row['business_name'] == 'help' and row['level'] == 'Component' # 1st condition
                           else (row['package'] if row['business_name'] == 'HELP' and row['level'] == 'Package' # 2nd condition
                                 else (row['reporting'] if row['business_name'] == 'PHELPS' # 3rd condition
                                       else np.nan) # NAN if no conditions matched
                           )
                       , axis=1)

相关问题 更多 >