Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the pandas data frame like this

YEAR_OPENED  2000 2001 2002 2003 2004 2005 2006 2007 2008 2009

 1999          1    0    0   0    1    0     0   0     1    0

 2000          1    1    2   0    3    0     0   0     0    0

 2001          0    0    0   4    0    0     0   0     0    0

I want to add all my values in a given column like this:

YEAR_OPENED   CLOSED_IN_5_YEARS

 1999               2

 2000               7

 2001               4

So basically I want to check if my column names fall in the five-year range of the corresponding values in the column 'YEAR_OPENED' and create the new column with a sum of all the values. How should I proceed?

1 Answer

0 votes
by (36.8k points)

You can use the below code:

df['CLOSED_IN_5_YEARS'] = df.set_index('YEAR_OPENED').apply(

        lambda x: sum(i for i, c in zip(x, x.index) if x.name <= int(c) <= x.name + 5), axis=1

    ).values

print(df)

Prints:

   YEAR_OPENED  2000  2001  2002  ...  2007  2008  2009  CLOSED_IN_5_YEARS

0         1999     1     0     0  ...     0     1     0                  2

1         2000     1     1     2  ...     0     0     0                  7

2         2001     0     0     0  ...     0     0     0                  4

Do you wish to learn Data Science from scratch? Enroll in this Data Science Courses

Browse Categories

...