python - 数据框根据与另一个数据框的比较过滤行

标签 python pandas dataframe filter

我想根据另一个数据帧的日期之间的日期过滤一个数据帧。

我尝试过以下代码:

df1 = pd.DataFrame({
                   'Start':['1/1/2016', '1/1/2016', '1/1/2016', '1/1/2016', '1/1/2016'], 
                    'end':['1/12/2016', '1/12/2016', '1/12/2016', '1/12/2016', '1/12/2016'], 
                   'Qty':[1, 2, 3, 4, 2],
                   })

df2 = pd.DataFrame({
                    'Start':['1/1/2016', '1/1/2016', '1/1/2016'], 
                    'end':['1/6/2016', '1/6/2016', '1/6/2016'], 
                    'Price':[11, 12, 31],
                   })

df2[(df2['Start']>=df1['Start']) & (df2['end']<=df1['end'])]

它应该选择 df2 的所有三行。但给出了这个错误:

ValueError:只能比较相同标签的Series对象

附注在我的例子中,行数不能相同。

最佳答案

  • pandas.to_datetime() - 将参数转换为日期时间。
  • DataFrame.reindex() - 使用可选的填充逻辑使 DataFrame 符合新索引,将 NA/NaN 放置在先前索引中没有值的位置。

例如

import pandas as pd

df1 = pd.DataFrame({
                   'Start':['1/1/2016', '1/1/2016', '1/1/2016', '1/1/2016', '1/1/2016'],
                    'end':['1/12/2016', '1/12/2016', '1/12/2016', '1/12/2016', '1/12/2016'],
                   'Qty':[1, 2, 3, 4, 2],
                   })

df2 = pd.DataFrame({
                    'Start':['1/1/2016', '1/1/2016', '1/1/2016'],
                    'end':['1/6/2016', '1/6/2016', '1/6/2016'],
                    'Price':[11, 12, 31],
                   })

# resize df2 shape
df2 = df2.reindex(df1.index)

# convert argument to datetime.
df1['Start'] = pd.to_datetime(df1['Start'])
df1['end'] = pd.to_datetime(df1['end'])

df2['Start'] = pd.to_datetime(df2['Start'])
df2['end'] = pd.to_datetime(df2['end'])

print(df2[(df2['Start'] >= df1['Start']) & (df2['end'] <= df1['end'])])

       Start        end  Price
0 2016-01-01 2016-01-06   11.0
1 2016-01-01 2016-01-06   12.0
2 2016-01-01 2016-01-06   31.0

关于python - 数据框根据与另一个数据框的比较过滤行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58267188/

相关文章:

python - 我在 python 中运行下面的代码并收到错误 'AttributeError: ' QgridWidget' object has no attribute 'to_excel' '

python - 如何在 pandas 中使用 count、groupby 和 max?

python - 使用 Pandas 每小时用特定列中的先前值填充每组缺失的日期

python - 动画散点图和等高线图

python - 有没有一种简单的方法可以消除 Python-pandas 中 DataFrame 中的重复行?

python - 如何根据匹配年份加上前 2 年从另一个数据框中提取多行

python - 使用类列表作为 django_tables2 中表类的模型

python - 从 scrapy 请求打印 'response'

python - 使用正则表达式替换文本文件中的多个条目

r - 在 SelectizeInput Shiny 中过滤多个输入的数据帧