Macterror
Macterror

Reputation: 431

Retrieve column name of last month of transactions in Pandas

Let's say I have a dataframe formatted the following way:

id | name | 052017 | 062017 | 072017 | 092017 | 102017

20 | abcd |  0     | 100    | 200    | 50     | 0

I need to retrieve the column name of the last month an organization had any transactions. In this case, I would like to add a column called "date_string" that would have 092017 as its contents.

Any way to achieve this?

Thanks!

Upvotes: 2

Views: 58

Answers (1)

BENY
BENY

Reputation: 323236

replace 0 to np.nan then using last_valid_index

df.replace(0,np.nan).apply(lambda x :x.last_valid_index(),1)
Out[602]: 
0     092017 
dtype: object

#df['newcol'] = df.replace(0,np.nan).apply(lambda x :x.last_valid_index(),1)

Upvotes: 5

Related Questions