如何遍历 pandas 数据帧,并有条件地将值赋给一行变量?

How to loop through pandas dataframe, and conditionally assign values to a row of a variable?

我正在尝试遍历 'vol' 数据框,并有条件地检查 sample_date 是否在特定日期之间。如果是,请为另一列赋值。

这是我的以下代码:

vol = pd.DataFrame(data=pd.date_range(start='11/3/2015', end='1/29/2019'))
vol.columns = ['sample_date']
vol['hydraulic_vol'] = np.nan
for i in vol.iterrows():
    if  pd.Timestamp('2015-11-03') <= vol.loc[i,'sample_date'] <= pd.Timestamp('2018-06-07'):
        vol.loc[i,'hydraulic_vol'] = 319779

这是我收到的错误: TypeError:'Series' 对象是可变的,因此它们不能被散列

这是正确的做法:

cond = (pd.Timestamp('2015-11-03') <= vol.sample_date) & 
       (vol.sample_date <= pd.Timestamp('2018-06-07'))

vol.loc[cond, 'hydraulic_vol'] = 319779

另一种方法是结合使用 numpy 模块中的 np.where 方法和 .between 方法。

这个方法是这样工作的:
np.where(condition, value if true, value if false)

代码示例

cond = vol.sample_date.between('2015-11-03', '2018-06-07')
vol['hydraulic_vol'] = np.where(cond, 319779, np.nan)

或者您可以将它们组合在一行代码中:

vol['hydraulic_vol'] = np.where(vol.sample_date.between('2015-11-03', '2018-06-07'), 319779, np.nan)

编辑
我看到你是新来的,所以这里有一些我必须学习的东西以及来到 python/pandas。

循环数据帧应该是你最后的选择,尝试使用 vectorized solutions,在这种情况下 .locnp.where,与循环相比,它们在速度方面表现更好.