python - 结合 np.equal 和 np.less 创建单个数据帧?

标签 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['Effective_Date'] 月份 = Date_Range 月份时返回 df1['Amount'] 的单个数据框。但是,如果 Date_Range 为 < df1['Effective_Date'],则返回 0。

例如,有效日期为 1/31/19,金额 = 5,对于 Date_Range = 1/31/19、1/31/20、1/31/21 等,则为 5,其他位置为 0。

我可以分别做这两部分:

如果月份相等:

df2 = (pd.DataFrame(np.equal.outer(df1.Effective_Date.dt.month, Date_Range.month) * df1.Amount.values[:,None], columns = Date_Range))

如果 Date_Range < 生效日期,则返回 0:

df3 = (pd.DataFrame(np.less_equal.outer(df1.Effective_Date, Date_Range) * df1['Amount'].values[:,None], columns = Date_Range))

但我不知道如何将两者结合起来。感谢你的帮助。

最佳答案

我相信你需要 numpy.where :

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]

关于python - 结合 np.equal 和 np.less 创建单个数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54231664/

相关文章:

python - 如何拆分数据帧值并将函数应用于列表的内容

python - 使用在另一个类的类方法中创建的变量

python - 将 env.yml 从 Anaconda 转换为 Pip req.txt

python - 在 Pandas 中将 float 转换为字符串

python - 列上的 Multiindiex str 替换

python - 如何将所有多值属性放入csv文件中

apache-spark - 动态重命名 PySpark DataFrame 中的多个列

python - Pandas - 根据另一列中引用的列名创建列

python - 对数据框 pandas 的列中存在的列表执行计算

python - 如何使用继承,我缺少什么?