Python 数据帧系列:检查是否存在特定值

Python 数据帧系列:检查是否存在特定值,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,如果列表中的值存在于其中一个dataframe列中,我需要迭代列表并执行特定操作。我试着按照下面的方法做,但发现了下面的错误 “错误:#序列的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all() 所需输出: fname age sal new_column Alex 20 100 5 <<-- sal/age Jane 15 200 200 <<-- sal as it is John

如果列表中的值存在于其中一个dataframe列中,我需要迭代列表并执行特定操作。我试着按照下面的方法做,但发现了下面的错误

错误:#序列的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all()

所需输出

fname   age sal new_column
Alex    20  100  5      <<-- sal/age
Jane    15  200  200    <<-- sal as it is
John    25  300  12     <<-- sal/age
fname age sal new_列

Alex 20 100 5使用
np.where
.isin
检查列是否包含特定值

df['new_column'] = np.where(
        df['fname'].isin(['Alex','John']),
        df['sal']/df['age'],
        df['sal']
)

print(df)

  fname  age  sal  new_column
0  Alex   20  100         5.0
1  Jane   15  200       200.0
2  John   25  300        12.0
纯熊猫版

df['new_column'] = (df['sal']/df['age']).where(
                            df['fname'].isin(['Alex','John']),other=df['sal'])


尝试使用
df。应用

将熊猫作为pd导入
人={
“fname”:[“亚历克斯”、“简”、“约翰”],
“年龄”:[20,15,25],
“萨尔”:[100200300]
}
df=pd.DataFrame(人)
def检查器(项目):
检查列表=['Alex','John']
如果检查表中的项目[“fname”]:
退货商品['sal']/商品['age']
其他:
退货项目['sal']
df[“Exists”]=df.apply(检查器,轴=1)
df

说明:若要在dataframe上循环,请使用iterrows(),row变量将为所有列提供值,index是该行的索引。

感谢DataKnower。有没有其他方法不用np.where就能做到这一点?@steve请看编辑。谢谢Mehul,它很有效。谢谢@PranayModukuru
df['new_column'] = (df['sal']/df['age']).where(
                            df['fname'].isin(['Alex','John']),other=df['sal'])
print(df)
 fname  age  sal  new_col
0  Alex   20  100      5.0
1  Jane   15  200    200.0
2  John   25  300     12.0
for index,row in df.iterrows():
    if row['fname'] in check_list:
           df.at[index,'new_column']=row['sal']/row['age']
    else:
           df.at[index,'new_column']=row['sal']