2017-10-10 95 views
0

我有一个数据帧,其中包含一系列名为balance的浮点数和一系列名为due_date的时间戳。我想创建一个名为current新列显示的balance如果due_date为> =今日(一切""),列名为1-30 Days显示的balance如果due_date为1至30天前(一切"")以及名为>30 Days的列,如果due_date超过30天前(其他所有""),则显示balance基于日期条件的新的大熊猫列

下面是一些例子行:

balance due_date 
0 250.00 2017-10-22 
1 400.00 2017-10-04 
2 3000.00 2017-09-08 
3 3000.00 2017-09-08 
4 250.00 2017-08-05 

任何帮助将不胜感激。

+0

这会帮助回答你的问题? https://stackoverflow.com/questions/11608238/is-it-possible-to-add-a-where-clause-with-list-comprehension – Brijesh

回答

1

使用pd.cutpd.crosstab

df['diff']=(pd.to_datetime('today')-df.due_date).dt.days 
df['New']=pd.cut(df['diff'],bins = [0,1,30,99999],labels=["current","1-30","more than 30"]) 
pd.concat([df,pd.crosstab(df.index.get_level_values(0),df.New).apply(lambda x: x.mul(df.balance))],axis=1) 


Out[928]: 
     balance due_date diff   New more than 30 
row_0              
0  250.0 2017-01-22 261 more than 30   250.0 
1  400.0 2017-02-04 248 more than 30   400.0 
2  3000.0 2017-02-08 244 more than 30  3000.0 
3  3000.0 2017-02-08 244 more than 30  3000.0 
4  250.0 2017-02-05 247 more than 30   250.0 
+0

工作很好。对箱子做了轻微的改动('[-50,0,30,99999]')以得到我以后的样子。 – neenertronics