【问题标题】:New pandas columns based on date condition基于日期条件的新熊猫列
【发布时间】:2017-10-10 20:43:13
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

标签: python pandas


【解决方案1】:

使用pd.cut 和pd.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

【讨论】:

  • 效果很好。对垃圾箱 ([-50,0,30,99999]) 稍作改动,以获得我想要的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 2021-07-11
  • 2021-08-27
  • 2018-11-15
相关资源
最近更新 更多