根据不同数据帧列中的值将第二个条件语句添加到“if”语句中

问题描述 投票:0回答:1

我目前有以下条件:

if not tops_subset.eq(row.iloc[2:4]).all(axis=1).any():

对于一些背景,它来自这个代码块:

tops_df = pd.read_csv('tops.csv', header=None)
tops_subset = tops_df.iloc[:, 2:4]
rows_written = 0

with open('for_email.csv', 'w', newline='') as for_email_file:
    for index, row in df_sorted_no_duplicates.iterrows():
        # Check if the third and fourth columns of the current row exist in 'tops.csv'
        if not tops_subset.eq(row.iloc[2:4]).all(axis=1).any():

它正确检查文件的任何行中是否已存在两列数据

tops.csv

我想修改 if 以便它适应第二个条件。 第二个条件是

tops_subset.eq(row.iloc[2:4]).all(axis=1).any()
为 true 并且数据存在的
tops.csv
行中倒数第二列的值为 0。

要明确的是,我希望 if 语句接受以下任一:

  1. 已经接受且带有
    not
    声明的那个

  1. 我上面描述的情况

我无法检查数据所在的行在倒数第二列中是否有 0。这就是我需要帮助的地方。

我试过这个:

if (tops_subset.eq(row.iloc[2:4]).all(axis=1).any() and tops_subset.iloc[:, -2].eq(0).any()) or not tops_subset.eq(row.iloc[2:4]).all(axis=1).any():

还有这个:

if (tops_subset.eq(row.iloc[2:4]).all(axis=1).any() and tops_subset.loc[tops_subset.eq(row.iloc[2:4]).all(axis=1), int(tops_subset.columns[-2])].eq(0).any()) or not tops_subset.eq(row.iloc[2:4]).all(axis=1).any():

两者都不起作用。

如有任何帮助,我们将不胜感激。

python pandas csv if-statement conditional-statements
1个回答
0
投票

你可以试试这个:

# Find matching rows in tops_subset
matching_rows = tops_subset.eq(row.iloc[2:4]).all(axis=1)

if not matching_rows.any() or (matching_rows.any() and (tops_df.iloc[matching_rows.index, -2] == 0).any()):
    # Your code here

© www.soinside.com 2019 - 2024. All rights reserved.