gpt4 book ai didi

python - Pandas:等效于 Excel sumifs

转载 作者:行者123 更新时间:2023-12-04 15:15:46 30 4
gpt4 key购买 nike

对于下表,我如何实现与以下 SUMIFS 语句等效的 Python?

SUMIFS(A3:A7,B3:B7,"<="&C1,C3:C7,">0")

enter image description here

DataFrame 代码:

dfp = pd.DataFrame({'Value': [1223, 34, 34, 345],
'Date': ['04/03/2020', '06/04/2020','08/06/2020','12/12/2020'],
'Tval' : [0.01,0.015,-0.023,-0.0005]})

预期输出为 1257。

最佳答案

这样就可以了:

from datetime import datetime as dt

# Define the reference date as a datetime object.
date = dt(2020, 12, 5)
# Convert dates to a datatime object for compare.
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')

# Apply filters and sum.
df.loc[(df['Tval'] > 0) & (df['Date'] <= date), 'Value'].sum()

输出:

>>> 1257

注意:以上假定国际日期格式 (D/M/Y)。

关于python - Pandas:等效于 Excel sumifs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64355132/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com