gpt4 book ai didi

python - 在 pandas 中填充 DataFrame

转载 作者:行者123 更新时间:2023-11-28 20:32:04 25 4
gpt4 key购买 nike

我正在尝试在 Pandas 中填充数据框。我尝试创建一个字典,然后将其放入数据框中,但没有成功。

这是我当前的代码:

holidays_dic= {
'Half_Summer17' :{'26-05-2017':'01-06-2017'}
,'Summer17' :{'21-07-2017':'31-08-2017'}
,'Half_Fall17' :{'20-10-2017':'26-10-2017'}
,'Xmas17' :{'20-12-2017':'02-01-2018'}
,'Half_Spring18' :{'12-02-2018':'16-02-2018'}
,'Easter18' :{'30-03-2018':'13-04-2018'}
,'Half_Summer18' :{'28-05-2018':'01-06-2018'}
,'Summer18' :{'25-07-2018':'04-09-2018'}
,'Half_Fall18' :{'22-10-2018':'25-10-2018'}
,'Xmas18' :{'20-12-2018':'03-01-2018'}
# ,'Half_Spring19' :{'01-01-2017':'01-01-2017'}
# ,'Easter19' :{'01-01-2017':'01-01-2017'}
}

df_holidays=pd.DataFrame(holidays_dic,)

#holidays_dic
df_holidays

我想要的输出是这样的:

index           sDate     eDate
Half_Summer17 26-05-17 01-06-17
Summer 17 21-07-17 31-08-17
etc

有没有人有什么想法?

最佳答案

你可以这样做:

import pandas as pd

holidays_dic = {
'Half_Summer17': {'26-05-2017': '01-06-2017'}
, 'Summer17': {'21-07-2017': '31-08-2017'}
, 'Half_Fall17': {'20-10-2017': '26-10-2017'}
, 'Xmas17': {'20-12-2017': '02-01-2018'}
, 'Half_Spring18': {'12-02-2018': '16-02-2018'}
, 'Easter18': {'30-03-2018': '13-04-2018'}
, 'Half_Summer18': {'28-05-2018': '01-06-2018'}
, 'Summer18': {'25-07-2018': '04-09-2018'}
, 'Half_Fall18': {'22-10-2018': '25-10-2018'}
, 'Xmas18': {'20-12-2018': '03-01-2018'}
}

data = [[holidays, start, end] for holidays, date_range in holidays_dic.items() for start, end in date_range.items()]
df = pd.DataFrame(data=data, columns=['holiday', 'sDate', 'eDate']).set_index(['holiday'])
print(df)

输出

                    sDate       eDate
holiday
Half_Summer18 28-05-2018 01-06-2018
Easter18 30-03-2018 13-04-2018
Xmas18 20-12-2018 03-01-2018
Xmas17 20-12-2017 02-01-2018
Half_Fall17 20-10-2017 26-10-2017
Half_Summer17 26-05-2017 01-06-2017
Summer18 25-07-2018 04-09-2018
Half_Fall18 22-10-2018 25-10-2018
Summer17 21-07-2017 31-08-2017
Half_Spring18 12-02-2018 16-02-2018

关于python - 在 pandas 中填充 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53152701/

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