Count specific values by python row

Asked 2 years ago, Updated 2 years ago, 59 views

Data frames that look like this

0 1 2 4
1 0 2 5
3 4 0 0

From

I want to print out the number of columns with zero in the last row with two zeros

Coding to be done

It's complicated.So the final result is to print out the numbers in columns 3 and 4.

It's not easy to get the results you want. It's hard to count the number of zeros in a data frame, so I'm asking you this question.

python dataframe

2022-09-20 20:01

1 Answers

I can do it like this.

import pandas as pd

df = pd.DataFrame([[0,1,2,4], [1,0,2,5],[3,4,0,0]])
# # print(df)

for row_idx, row in enumerate(df.itertuples(index=False)):
    if row.count(0) >= 2:
        # # print(row)
        print(row_idx+1)
        print(" ".join([ str(i+1) for i, d in enumerate(row) if d == 0 ]))


2022-09-20 20:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.