基于 date_time 索引值的 Python/pandas 条件语句

标签 python datetime pandas conditional-statements

我有一个 Pandas 数据框,其时间序列索引基于使用 date_time 应用的日期范围,如下所示:

                     Column A
2016-11-24 00:00:00  4.0
2016-11-24 01:00:00  7.8
2016-11-24 02:00:00  95.1
2016-11-24 03:00:00  78.4
etc

我想要做的是创建一个新列,根据索引中的月份将因子应用于 A 列。

修正系数:9 月 = 1、10 月 = 2、11 月 = 3、12 月 = 4 等。

因此,在上面的示例中,由于月份是 11 月,因此结果将是:

                     Column A   Column B
2016-11-24 00:00:00  4.0        12
2016-11-24 01:00:00  7.8        23.4
2016-11-24 02:00:00  95.1       285.3
2016-11-24 03:00:00  78.4       235.2
etc

我尝试了多种解决方案,但都遇到了一些问题。有人有什么建议吗?

最佳答案

我认为你可以从 month 中减去 8然后多个,但在九月之前的几个月内,获得的数字少于1:

print (df.index.month - 8)
[3 3 3 3]

df['Column B'] = df['Column A'] * (df.index.month - 8)
print (df)
                     Column A  Column B
2016-11-24 00:00:00       4.0      12.0
2016-11-24 01:00:00       7.8      23.4
2016-11-24 02:00:00      95.1     285.3
2016-11-24 03:00:00      78.4     235.2

您还可以使用map乘以 dict,然后乘以 mul 。在此解决方案中,需要从 df.index.month 创建 Series,它返回索引为 dfnumpy array (如果不是index,则获取所有值NaN,因为索引不匹配)。

d = {9:1,10:2,11:3,12:4}

df['Column B'] = pd.Series(df.index.month, index=df.index).map(d).mul(df['Column A'])
print (df)
                     Column A  Column B
2016-11-24 00:00:00       4.0      12.0
2016-11-24 01:00:00       7.8      23.4
2016-11-24 02:00:00      95.1     285.3
2016-11-24 03:00:00      78.4     235.2

关于基于 date_time 索引值的 Python/pandas 条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40844480/

相关文章:

c# - 如何检查 DateTime 是否发生在今天?

python - 如何在具有时区感知时间戳列的数据帧上附加?

python - 根据许多不同列的条件从数据框中删除行

python - 使用 pandas 进行多变量分组操作

python - 从扭曲的服务器向特定客户端发送数据

python - 使用R/python/Mapreduce可以计算单词共现吗?

python 概率

python - 仅将天数和时间(小时 x 分钟 x 秒)转换为时间

python - SQLAlchemy + cx_oracle 和特殊字符

c# - 记录和计算时间的方法是什么?