Pandas数据框系列:检查特定值是否存在

5
我需要遍历一个列表,并在该列表的值存在于Pandas数据帧某一列时执行特定操作。我尝试以下方法,但是出现了下面的错误:错误:#序列的真值不明确。请使用a.empty、a.bool()、a.item()、a.any()或a.all()。
注:Pandas是Python语言中的一个数据处理库,它常用于数据分析、机器学习等领域。
import pandas as pd

people = {
    'fname':['Alex','Jane','John'],
    'age':[20,15,25],
    'sal':[100,200,300]
}

df=pd.DataFrame(people)

check_list=['Alex','John']

for column in check_list:
    if (column == df['fname']):
        df['new_column']=df['sal']/df['age']
    else:
        df['new_column']=df['sal']

df

所需输出:

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
3个回答

6
使用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

纯粹的Pandas版本。

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

谢谢Datanovice。有没有其他方法可以不使用np.where来完成这个任务? - steve
@Steve 看编辑。 - Umar.H

2
尝试使用df.apply
import pandas as pd

people = {
    'fname':['Alex','Jane','John'],
    'age':[20,15,25],
    'sal':[100,200,300]
}

df=pd.DataFrame(people)

def checker(item):
    check_list=['Alex','John']
    if item["fname"] in check_list:
        return item['sal']/item['age']
    else:
        return item['sal']

df["Exists"] = df.apply(checker, axis=1)

df



1
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']

使用iterrows()循环遍历数据框,行变量将具有所有列的值,索引是行的索引。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接