gpt4 book ai didi

python - 具有本地化日期时间索引的数据帧 : Drop every row but those who exists in another dataframe

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:30 24 4
gpt4 key购买 nike

我有一个如下所示的数据框 A:

2018-01-02 09:35:00-05:00    1.238914e-01
2018-01-02 09:40:00-05:00 2.125115e-02
2018-01-02 09:45:00-05:00 1.969027e-02
2018-01-02 09:50:00-05:00 1.467054e-02
2018-01-02 09:55:00-05:00 1.831057e-02
2018-01-02 10:00:00-05:00 1.714546e-02
2018-01-02 10:05:00-05:00 1.515882e-02
2018-01-02 10:10:00-05:00 1.096963e-02
2018-01-02 10:15:00-05:00 9.687181e-03
2018-01-02 10:20:00-05:00 9.098983e-03
2018-01-02 10:25:00-05:00 8.747766e-03
2018-01-02 10:30:00-05:00 1.227635e-02
2018-01-02 10:35:00-05:00 9.554932e-03
2018-01-02 10:40:00-05:00 1.012054e-02

还有一个 B,如下所示:

2018-01-02 09:35:00-05:00    1.95814e-01
2018-01-02 10:35:00-05:00 9.551878-03
2018-01-02 10:40:00-05:00 8.000478-03

我需要将 A 转换为:

2018-01-02 09:35:00-05:00    1.238914e-01
2018-01-02 10:35:00-05:00 9.554932e-03
2018-01-02 10:40:00-05:00 1.012054e-02

即:删除 A 中的每一行,但 B 中退出的行除外。

所以我正在做:

a_df = pd.read_csv(a_file, index_col=0, parse_dates=True)
b_df = pd.read_csv(b_file, index_col=0, parse_dates=True)

a_df.index = pd.to_datetime(a_df.index, utc=True)
b_df.index = pd.to_datetime(b_df.index, utc=True)

最后

a_df = a_df.loc[b_df.index, a_df.columns]

但是我得到了

 ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True

Pandas 0.24.2

最佳答案

你介意尝试一下吗:

#create some test data
dfa = pd.DataFrame({"index": ["2018-01-02 09:35:00-05:00", "2018-01-02 09:40:00-05:00", "2018-01-02 09:45:00-05:00", "2018-01-02 09:50:00-05:00"],
"values": [1.238914e-01, 2.125115e-02, 1.969027e-02, 1.467054e-02]}).set_index("index")
dfb = pd.DataFrame({"index": ["2018-01-02 09:35:00-05:00", "2018-01-02 09:40:00-05:00"],
"values": [1.238914e-01, 2.125115e-02]}).set_index("index")

#convert to date time object
dfa.index = pd.to_datetime(dfa.index, utc=True)
dfb.index = pd.to_datetime(dfb.index, utc=True)

#select to appropriate indices
dfa[dfa.index.isin(dfb.index)]

输出:

                    index   values
2018-01-02 14:35:00+00:00 0.123891
2018-01-02 14:40:00+00:00 0.021251

我在 dfb 的索引上使用 isin 来实现 dfa 索引的 bool 选择。

关于python - 具有本地化日期时间索引的数据帧 : Drop every row but those who exists in another dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59046955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com