Home > front end >  pandas count rows with constant columns
pandas count rows with constant columns

Time:11-10

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!

CodePudding user response:

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
  • Related