Python 结合np.equal和np.less创建单个数据帧?
我有以下资料:Python 结合np.equal和np.less创建单个数据帧?,python,pandas,dataframe,outer-join,Python,Pandas,Dataframe,Outer Join,我有以下资料: df1 = pd.DataFrame({'Effective_Date':pd.to_datetime(['12/31/2017', '1/31/2018', '2/28/2018', '3/31/2018', '9/30/2020']), 'Amount':[100,150,300,500,750]}) Date_Range = pd.date_range('12/31/2017', periods=150, freq='M') 我试图创建
df1 = pd.DataFrame({'Effective_Date':pd.to_datetime(['12/31/2017', '1/31/2018', '2/28/2018', '3/31/2018', '9/30/2020']),
'Amount':[100,150,300,500,750]})
Date_Range = pd.date_range('12/31/2017', periods=150, freq='M')
我试图创建一个数据帧,当df1的月份['Effective_Date']=日期的月份范围时返回df1['Amount']。但是,如果日期范围小于df1[“生效日期”),则返回0
例如,如果生效日期为19年1月31日,金额为5,则日期范围为19年1月31日、20年1月31日、21年1月31日等的生效日期为5,其他日期为0
我可以分别做这两件事:
如果月份相等:
df2 = (pd.DataFrame(np.equal.outer(df1.Effective_Date.dt.month, Date_Range.month) * df1.Amount.values[:,None], columns = Date_Range))
如果日期范围<生效日期,则返回0:
df3 = (pd.DataFrame(np.less_equal.outer(df1.Effective_Date, Date_Range) * df1['Amount'].values[:,None], columns = Date_Range))
但我不知道如何将两者结合起来。谢谢你的帮助 我相信您需要:
a=np.equal.outer(df1.effect_Date.dt.month,Date_Range.month)*df1.Amount.value[:,无]
b=np.减去等于外部(df1.生效日期,日期范围)*df1[‘金额’]。值[:,无]
m=日期范围值
您能添加一些数据样本吗?很抱歉,UpdatedTanks Jezrael。我认为这已经很接近了,但还有一些事情需要解决:1)a系列似乎不再有效了。我希望19年1月15日的生效日期仅在1月显示金额,因此19年1月31日、20年1月31日、21年1月31日等。此外,20年9月30日的生效日期似乎从2018年9月30日开始,但我希望在20年9月30日之前为0。@EChan-您能创建吗?不容易测试(可能仅1-2个月的数据)
a = np.equal.outer(df1.Effective_Date.dt.month, Date_Range.month) * df1.Amount.values[:,None]
b = np.less_equal.outer(df1.Effective_Date, Date_Range) * df1['Amount'].values[:,None]
m = Date_Range.values < df1['Effective_Date'].values[:,None]
df = pd.DataFrame(np.where(m, a, b), columns = Date_Range)
print (df)
2017-12-31 2018-01-31 2018-02-28 2018-03-31 2018-04-30 2018-05-31 \
0 100 100 100 100 100 100
1 0 150 150 150 150 150
2 0 0 300 300 300 300
3 0 0 0 500 500 500
4 0 0 0 0 0 0
2029-12-31 2030-01-31 2030-02-28 2030-03-31 2030-04-30 \
0 ... 100 100 100 100 100
1 ... 150 150 150 150 150
2 ... 300 300 300 300 300
3 ... 500 500 500 500 500
4 ... 750 750 750 750 750
2030-05-31
0 100
1 150
2 300
3 500
4 750
[5 rows x 150 columns]