Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas count rows with constant columns

I have a pandas df with the following structure

Car       2020-01-01  2020-01-02    2020-01-03
Car1       10          10             10
Car2       0           10             10
Car3       5          15              7

I want to create a IS_CONSTANT column for non zero values, such that if a row has a constant non-zero value, it the IS_CONSTANT column is set to 1
The resulting df would be

Car       2020-01-01  2020-01-02    2020-01-03  IS_CONSTANT
Car1       10          10             10           1
Car2       0           10             10           1
Car3       5          15              7            0

Is there a pythonic way of doing this? One option would be a loop but might be inefficient for large dataset.
Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do nunique

df['new'] = df.set_index('Car').mask(lambda x: x==0).nunique(1).eq(1).astype(int).values
df
Out[385]: 
    Car  2020-01-01  2020-01-02  2020-01-03  new
0  Car1          10          10          10    1
1  Car2           0          10          10    1
2  Car3           5          15           7    0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading