繁体   English   中英

根据一列中的条件创建一个新的pandas列,并在同一数据框中分配多个列中的值

[英]create a new pandas column based on condition in one column and assigning the value from multiple columns in the same data frame

我试图基于一个列中的条件创建一个新列,并从同一数据框中的多个列中分配值。

下面是我尝试过的代码。

data["Associate"]= data.apply(lambda x: np.where(x.BU=='SBS',x.SBS,x.MAS_NAS_HRO),axis=1)

在此处输入图片说明

BU    SBS       MAS_NAS_HRO   Associate
SBS   Ren       Sunil         Ren
MAS   Uma       Majid         Majid
NAS   Sumit     Uma           Uma

上面的图像是我正在尝试实现的错误:

ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series

我也尝试过

data['Associate']=''
data.loc[data['BU'] == 'SBS',Associate]=data['SBS']

我尝试了一下,但也没有用。

associate_details=['SBS']
associate1=data[data.BU.isin(associate_details)]
choice_assoc1=efile_data['SBS']
associate2=data[~data.BU.isin(associate_details)]
choice_assoc2=efile_data['MAS_NAS_HRO']
efile_data['Associate']=np.select([associate1,associate2],[choice_assoc1,choice_assoc2],default=np.nan)

i get this message [0 rows x 4 columns]
Empty DataFrame

我该如何更改这些错误。

问候,任。

我不确定您的第一段代码为什么不起作用,因为它对我有用,但是您可以尝试以下其他方法之一。

我在python 3.7.3上使用numpy 1.16.4版本和pandas 0.24.2版本。

data = {
    'BU': ['SBS', 'MAS', 'NAS'],
    'SBS': ['Ren', 'Uma', 'Sumit'],
    'MAS_NAS_HRO': ['Sunil', 'Majid', 'Uma']
}
df = pd.DataFrame(data)

# The following all work, but I prefer no. 3. It's faster and more concise.

# 1. Using apply with lambda and if statement
df['Associates'] = df.apply(lambda row: row['SBS'] if row['BU'] == 'SBS' else row['MAS_NAS_HRO'], axis=1)

# 2. Using apply with lambda and np.where (op's method)
df["Associate"] = df.apply(lambda x: np.where(x.BU=='SBS', x.SBS, x.MAS_NAS_HRO), axis=1)

# 3. Using np.where only (s/o to @Erfan)
df['Associate'] = np.where(df['BU']=='SBS', df['SBS'], df['MAS_NAS_HRO'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM