【问题标题】:Error while using index of one dataframe to acess the row of another dataframe使用一个数据帧的索引访问另一个数据帧的行时出错
【发布时间】:2023-04-08 00:12:02
【问题描述】:

我有两个不同的数据框,df1 和 df2。 df1 由从初始日期到最终日期的完整日期系列索引; df2 从必须在 df1 中的日期索引,但它的索引是 df1 索引的子集。我正在尝试遍历 df1.index 并使用以下代码验证 df1 的特定索引值是否存在于 df2:

from datetime import timedelta
import datetime
import pandas as pd


for idx in df1.index:
    if idx in df2.index:
        print(df2.loc[idx])

我面临的问题是 df2 的某些索引产生 if 语句,而有些则不是。例如:

sdate = datetime.date(2020, 5, 4)
edate = datetime.date(2020, 10, 1)
some_date = edate - timedelta(days=2)
# df1 with all the dates
df1 = pd.DataFrame(index=pd.date_range(sdate,edate-timedelta(days=1),freq='d'))
# df2 with only two dates (sdate and some_date)
df2 = pd.DataFrame(index=[sdate, some_date])

当我尝试运行以下代码时,它会产生 False

df1.loc[some_date].name in df2.index
>>> False

虽然some_date 显然在 df2.index 中

some_date in df2.index
>>> True

在与 df2.index 的比较中,首先显示df1.loc[some_date].name 的返回不兼容,但在尝试运行以下代码时,会观察到不同的行为:

df1.loc[sdate].name in df2.index
>>> True
sdate in df2.index
>>> True

这到底是如何工作的?

【问题讨论】:

    标签: python pandas dataframe indexing


    【解决方案1】:

    错误是因为数据类型不同。
    df1.indexdatetimedf2.indexdate
    试试这样:

    df1.index.normalize()
    for idx in df2.index:
        if idx in df2.index:
            print(df2.loc[idx])
    

    或者,用日期时间替换日期:

    sdate = datetime.datetime(2020, 5, 4)
    edate = datetime.datetime(2020, 10, 1)
    

    【讨论】:

    • 这并没有回答有关sdate 索引和some_date 索引行为的问题。
    • 你能解释一下问题是什么吗?我测试了你的代码,至少在我的 python 版本中,df1.loc[some_date].name in df2.indexdf1.loc[sdate].name in df2.index 行产生“KeyError”。将 date(sdate 或 some_date)与 datetime(df1.index)进行比较是无效的。
    猜你喜欢
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2020-03-13
    • 2020-09-18
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多