检索Pandas上个月交易的列名

Mac*_*ror 2 python pandas

假设我的数据帧格式如下:

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

20 | abcd |  0     | 100    | 200    | 50     | 0
Run Code Online (Sandbox Code Playgroud)

我需要检索组织有任何交易的上个月的列名.在这种情况下,我想添加一个名为"date_string"的列,它将092017作为其内容.

有没有办法实现这个目标?

谢谢!

WeN*_*Ben 5

replace0 np.nan然后使用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)
Run Code Online (Sandbox Code Playgroud)