【问题标题】:Most efficient way to alter dataframe rows given a set condition给定条件下更改数据帧行的最有效方法
【发布时间】:2021-01-16 01:16:33
【问题描述】:

我知道有几种方法可以解决这个问题,但我想实施最有效的方法。

在给定条件的情况下,我需要向特定数据框行添加 1 或 2。我已经创建了一个布尔值掩码。调整后的列将是预测。

代码如下:

df = pd.DataFrame({'Date': preds_date,
                   'HE': HE_results,
                  'Predictions': y_pred})

#adjust model to capture peaks better
adjustHours = [6, 7, 15]
adjustHours_2 = [16, 17, 18, 19]

add1 = df['HE'].isin(adjustHours)

基本上 - 我正在查看每小时数据,如果布尔值为 True,那么我想将预测列调整 1 或 2 - 取决于是在第一个数组还是第二个数组中。

这里的 add1 是 True 和 False 的布尔掩码,在这种情况下,如果小时是 6,7 或 15,则为 True。

谢谢!

【问题讨论】:

  • 应该类似于df.loc[add1, 'Predictions'] += 1。第二个列表类似。也应该非常有效,但您应该对其进行测试。

标签: python pandas dataframe


【解决方案1】:

IIUC,创建adjust_by_hour 映射,然后在HE 列上使用map 方法给出相应的调整时间:

adjust_by_hour = {6:1, 7:1, 15:1, 16:2, 17:2, 18:2, 19:2}
new_pred = df['Predictions'] + df['HE'].map(lambda x: adjust_by_hour.get(x, 0))

例子

adjust_by_hour = {6:1, 7:1, 15:1, 16:2, 17:2, 18:2, 19:2}

he = pd.Series([6, 18, 3])
he   
#0     6
#1    18
#2     3
#dtype: int64

he.map(lambda x: adjust_by_hour.get(x, 0))
#0    1
#1    2
#2    0
#dtype: int64

【讨论】:

  • 使用“map”意味着为每一行运行一个 Python 函数。这对我来说似乎不是很有效。
  • @MichaelButscher 是的,这取决于数据的大小。使用np.where 可能会获得更多性能,但由于条件是完全自定义的。代码可能会变得非常冗长。
【解决方案2】:

您想在 df['predictions'] 中的值中添加一个数字,其中 df['HE'] 具有特定值?

您可能应该使用wheremask。它们的功能基本相同; where 执行 test_condition 为 false 的操作,mask 执行 test_condition 为 true 的操作。

df = pd.DataFrame({'Date': preds_date,
                   'HE': HE_results,
                  'Predictions': y_pred})

#adjust model to capture peaks better
adjustHours = [6, 7, 15]
adjustHours_2 = [16, 17, 18, 19]

## Here's the mask call, one easy line. 
df['Predictions'].mask(df['HE'].isin(adjustHours), df['Predictions'] += 1, inplace=True)

掩码的基本语法是pd.Series.mask(test_cond, other=nan, inplace=False) 还有一些其他的kwargs。 other=... 指定用什么替换 pd.Series 中的值,例如 pd.Series +1。只要 other 是可向量化的操作, mask 就非常快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-23
    • 2019-12-10
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多