gpt4 book ai didi

python - pandas DataFrame 从 MultiIndex 日期索引中获取每年的第一天

转载 作者:太空宇宙 更新时间:2023-11-04 05:00:37 28 4
gpt4 key购买 nike

我有这个数据框:

dft2 = pd.DataFrame(np.random.randn(20, 1),
columns=['A'],
index=pd.MultiIndex.from_product([pd.date_range('20130101',
periods=10,
freq='4M'),
['a', 'b']]))

当我打印它时,它看起来像这样。

输出:

                A
2013-01-31 a 0.275921
b 1.336497
2013-05-31 a 1.040245
b 0.716865
2013-09-30 a -2.697420
b -1.570267
2014-01-31 a 1.326194
b -0.209718
2014-05-31 a -1.030777
b 0.401654
2014-09-30 a 1.138958
b -1.162370
2015-01-31 a 1.770279
b 0.606219
2015-05-31 a -0.819126
b -0.967827
2015-09-30 a -1.423667
b 0.894103
2016-01-31 a 1.765187
b -0.334844

如何按当年最小的行选择过滤器?像 2013-01-312014-01-31 吗?

谢谢。

最佳答案

# Create dataframe from the dates in the first level of the index.
df = pd.DataFrame(dft2.index.get_level_values(0), columns=['date'], index=dft2.index)

# Add a `year` column that gets the year of each date.
df = df.assign(year=[d.year for d in df['date']])

# Find the minimum date of each year by grouping.
min_annual_dates = df.groupby('year')['date'].min().tolist()

# Filter the original dataframe based on these minimum dates by year.
>>> dft2.loc[(min_annual_dates, slice(None)), :]
A
2013-01-31 a 1.087274
b 1.488553
2014-01-31 a 0.119801
b 0.922468
2015-01-31 a -0.262440
b 0.642201
2016-01-31 a 1.144664
b 0.410701

关于python - pandas DataFrame 从 MultiIndex 日期索引中获取每年的第一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45842646/

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