在Pandas数据框列上应用条件

时间:2019-08-26 02:35:32

标签: python pandas dataframe

我有一个熊猫数据框[df],如下所示:

ID  Status  
1   Success
2   Success
3   Fail
4   nan

基本上,如果所有状态均为“成功”,则我要打印“成功”,否则要打印“失败”。看起来很简单,但我不知道我在做什么错。

我正在尝试以下代码:

if df['Status'].values.all() == "SUCCESSFUL":
    print("=" * 128 + "\n" + "Success")
else:
    print("=" * 128 + "\n" + "Fail")

OR

if df['Status'].isnull().values.any() == False and df['Status'].values.all() == "SUCCESSFUL":
    print("=" * 128 + "\n" + "Success")
elif df['Status'].isnull().values.any() == True or df['Status'].values.any() != "SUCCESSFUL":
    print("=" * 128 + "\n" + "Fail")

这些方法似乎都不起作用。他们给我的结果是“成功”。

4 个答案:

答案 0 :(得分:1)

您应该使用布尔值all

if ((df['Status'] == "SUCCESSFUL") |(df['Status'].isnull())).all():
    print("=" * 128 + "\n" + "Success")
else:
    print("=" * 128 + "\n" + "Fail")
================================================================================================================================
Fail

答案 1 :(得分:1)

if (df['Status']=='Fail').any():
    print('Failed')
else:
    print('Passed')

if (df['Status']=='Success').all():
    print('Passed')
else:
    print('Failed')

答案 2 :(得分:1)

这应该有效:

public Optional<Hospital> findById(String id) {
   int parsedInt = Integer.parseInt(id);
   return hospitalRepository.findById(parsedInt);
}

@Query("SELECT *, ( 6371 * acos( cos( radians(?1) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( ?2) ) + sin( radians(?1) ) * sin( radians( lat ) ) ) ) AS distance FROM hospital HAVING distance < 8.5 ORDER BY distance LIMIT 0 , 20")
public List<Hospital> findHospitalByZipcode(String zipcode) throws InterruptedException, ApiException, IOException {
    double[] coords = ZipodePoint(zipcode);   
    return hospitalRepository.findByLatAndLng(coords[0], coords[1]);
}

答案 3 :(得分:1)

if df['Status'].size == sum(df['Status'] == 'Success'):
    print("=" * 128 + "\n" + "Success")
else:
    print("=" * 128 + "\n" + "Fail")