gpt4 book ai didi

python - 从多索引中获取唯一索引的值

转载 作者:行者123 更新时间:2023-12-01 09:30:11 24 4
gpt4 key购买 nike

df 是一个如下所示的数据集。列名,日期是一个多索引,值是相应的数据(代表股票的美元价格)

                               value
name date
122630 KS Equity 2013-01-02 13495.0
2013-01-03 13400.0
2013-01-04 13195.0
2013-01-07 13220.0
2013-01-08 12960.0
2013-01-09 12850.0
2013-01-10 13080.0
2013-01-11 12910.0
2013-01-14 13050.0
2013-01-15 12765.0
2013-01-16 12570.0
2013-01-17 12595.0
2013-01-18 12690.0
2013-01-21 12735.0
2013-01-22 12880.0
2013-01-23 12630.0
2013-01-24 12415.0
... ...
278240 KS Equity 2018-03-19 22855.0
2018-03-20 23690.0
2018-03-21 23275.0
2018-03-22 22285.0
2018-03-23 19460.0
2018-03-26 21110.0
2018-03-27 21080.0
2018-03-28 20535.0
2018-03-29 21605.0
2018-03-30 21785.0
291630 KS Equity 2018-03-16 9980.0
2018-03-19 9680.0
2018-03-20 10025.0
2018-03-21 9865.0
2018-03-22 9420.0
2018-03-23 8225.0
2018-03-26 8930.0
2018-03-27 8915.0
2018-03-28 8680.0
2018-03-29 9165.0
2018-03-30 9230.0
292340 KS Equity 2018-03-20 10050.0
2018-03-21 10050.0
2018-03-22 10090.0
2018-03-23 9750.0
2018-03-26 9815.0
2018-03-27 9925.0
2018-03-28 9745.0
2018-03-29 9890.0
2018-03-30 9970.0

问题是“如何制作一个唯一的日期时间数据集,其中包含上面的所有日期但不包含重复项?

all_dates = [datetime(2013,1,2,0), datetime(2013,1,3,0), datetime(2013,1,4,0),...datetime(2018,3,29,0), datetime(2018,3,30,0)]

我尝试了df.index(1).value,但它给出了错误''MultiIndex'对象不可调用'

最佳答案

使用get_level_values首先,然后 unique最后转换为列表:

L = df.index.get_level_values('date').unique().tolist()
print (L[:10])
[Timestamp('2013-01-02 00:00:00'), Timestamp('2013-01-03 00:00:00'),
Timestamp('2013-01-04 00:00:00'), Timestamp('2013-01-07 00:00:00'),
Timestamp('2013-01-08 00:00:00'), Timestamp('2013-01-09 00:00:00'),
Timestamp('2013-01-10 00:00:00'), Timestamp('2013-01-11 00:00:00'),
Timestamp('2013-01-14 00:00:00'), Timestamp('2013-01-15 00:00:00')]

对于纯Python日期时间添加to_pydatetime :

L = df.index.get_level_values('date').unique().to_pydatetime().tolist()
print (L[:10])
[datetime.datetime(2013, 1, 2, 0, 0), datetime.datetime(2013, 1, 3, 0, 0),
datetime.datetime(2013, 1, 4, 0, 0), datetime.datetime(2013, 1, 7, 0, 0),
datetime.datetime(2013, 1, 8, 0, 0), datetime.datetime(2013, 1, 9, 0, 0),
datetime.datetime(2013, 1, 10, 0, 0), datetime.datetime(2013, 1, 11, 0, 0),
datetime.datetime(2013, 1, 14, 0, 0), datetime.datetime(2013, 1, 15, 0, 0)]

关于python - 从多索引中获取唯一索引的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50039425/

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