[英]How to iterate over rows and index in a DataFrame in Pandas to filter bolean values
[英]Pandas: Iterate over dataframe rows using date filter
我有一個數據框,其中包含一系列日期和相應的值。 我有另一個包含三列(最小日期,最大日期,值)的數據框。 我想使用第二個數據幀mindate和maxdate遍歷第一個數據幀的每一行。 然后,我想將每個值乘以新范圍 df中的CustomerUsage並返回總和。
>>df1 Date Value
0 2012-04-01 0.00275
1 2012-04-02 0.00278
2 2012-04-03 0.00369
3 2012-04-04 0.00268
4 2012-04-05 0.00400
>>df2 Start End CustomerUsage
1 2012-04-01 2012-04-03 464.0
2 2012-04-04 2012-04-04 472.1
>> for row in df2.iterrows():
mindate = row[row.index[0],'Start']
maxdate = row[row.index[0],'End']
range = df1[(df1['Dates'] >= mindate) & (df1['Dates'] <= maxdate)]
range['Calc'] = range['Value']*df2['CustomerUsage']
##numpy .agg function here##
一行可以工作,但是我被困在遍歷日期, AttributeError錯誤:'str'對象沒有屬性'loc' (我收集到我在錯誤地對待這些元組,但是不確定補救措施!)
非常感謝!
好吧,所以我得到了以下答案。 絕對碰到了幾條@Wen帖子哈哈
#created an ID
list_ = []
df1.insert(0,'ID',range(0,0+len(df1)))
for index, row in df1.iterrows():
start = row['start']
end = row['end']
range = df2[(df2['date']>=start) & (df2['date']<=end)]
df2['ID'] = row['ID']
list_.append(df2)
batch = pd.concat(list_)
_small = batch.groupby(['ID']).agg({'value': np.sum})
_merge = batch.reset_index().merge(_small.reset_index(), how = 'left', on = ['ID']
我正在嘗試itertuples,因為我正在更快地閱讀它。 速度至關重要,因此如果有人進行升級... :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.