基于日期条件的新pandas列

时间:2017-10-10 20:43:13

标签: python pandas

我有一个数据框,其中包含一系列名为balance的浮点数和一系列名为due_date的时间戳。我想要创建一个名为current的新列,如果balance是> =今天(所有其他due_date),则会显示"" 1-30 Days如果balance是1到30天之前显示due_date(其他所有""),则会显示>30 Days,显示balance 1}}如果due_date超过30天(其他所有"")。

以下是一些示例行:

    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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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