具有 2 个条件的 Python Dataframe Vlookup

标签 python dataframe

我有一个包含多个日期/时间/价格的数据框,但喜欢每天提取 1600 的价格来创建一个新列 (Priceat1600)。 (因此需要在 1600 处查找日期和时间)

原始数据框

    Date  Time     Price
20090130   955  25641.00
20090130   956  25666.60
20090130   959  25746.10
20090130  1000  25794.80
20090130  1006  26023.10
20090130  1600  26000.00
.
.
.
20160902  1600     35.00
20160902  1903     34.84
20160902  1908     34.85
20160902  1912     34.85
20160902  1914     34.85
20160902  1915     34.83

我正在寻找的输出

    Date  Time     Price  Priceat1600
20090130   955  25641.00        26000
20090130   956  25666.60        26000
20090130   959  25746.10        26000
20090130  1000  25794.80        26000
20090130  1006  26023.10        26000
20090130  1600  26000.00        26000
.
.
.
20160902  1600     35.00       35.00
20160902  1903     34.84       35.00
20160902  1908     34.85       35.00
20160902  1912     34.85       35.00
20160902  1914     34.85       35.00
20160902  1915     34.83       35.00

最佳答案

根据您的数据,mask + groupby + transform + first/min/max 效果很好:

df.Price.mask(~df.Time.eq(1600)).groupby(df.Date).transform('first')

0     26000.0
1     26000.0
2     26000.0
3     26000.0
4     26000.0
5     26000.0
6        35.0
7        35.0
8        35.0
9        35.0
10       35.0
11       35.0
Name: Price, dtype: float64
  1. 屏蔽下午 4 点未记录的所有 Price
  2. 日期分组,并使用transform在每组的所有行中复制这些值

您可以将结果分配回df['Priceat1600']

关于具有 2 个条件的 Python Dataframe Vlookup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49132889/

相关文章:

python - 如何设置目标参数来使用 scipy.optimize 解决多目标问题?

python - 无法导入动态安装的python模块

python - 如何在 Python 中使用带前缀的 str.get_dummies?

python - Pandas 与不同频率的数据帧合并(每小时和每天)

python - 在 Python 中替换 DataFrame 的所有单元格中的值

python - 如何在 Ubuntu 16.04 上完全卸载 python 2.7.13

python - 类里面有额外的键值对吗?

Python TDD目录结构

python - 总结 Pandas 数据框中的部分列

python - 如何从 Pandas 的数据框中提取单元格值