如何在两列中获得仅1s的输出?

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

我有一个包含数据的 csv 文件。 从该文件中,我只需要 1,每一行中都不止一个。 例子: 1| A 栏 | B 栏 | 2| -------- | -------- | 3| 1 | 1 | 4| 1 | 0 | 我应该只打印第四行。 谁能帮我这个吗???

我应该得到两列中都包含 1 的输出。

python google-colaboratory collaboration
1个回答
0
投票

当然!为了实现仅打印两列都多次出现值 1 的行的要求,您可以使用 Python 和 csv 模块。这是一个执行此操作的脚本:

import csv

# Open the CSV file for reading
with open('your_file.csv', 'r', newline='') as csv_file:
    csv_reader = csv.reader(csv_file)

    # Skip the header row
    next(csv_reader)

    # Iterate through each row
    for row in csv_reader:
        # Count occurrences of '1' in columns A and B
        count_col_a = row[1:].count('1')  # Skip the first column (index 0)
        count_col_b = row[2:].count('1')  # Skip the first two columns

        # Check if both columns have more than one '1'
        if count_col_a > 1 and count_col_b > 1:
            print('|'.join(row))  # Print the entire row

将“your_file.csv”替换为 CSV 文件的路径。该脚本读取 CSV 文件,跳过标题行,然后计算每行 A 列和 B 列中 1 的出现次数。如果两列都出现多次 1,则会打印整行。

确保您的系统上安装了 Python,并且您可以通过在终端或命令提示符中执行脚本来运行该脚本。

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