gpt4 book ai didi

python - 用缺失日期填充其他列 Nan Pandas DataFrame

转载 作者:行者123 更新时间:2023-12-04 01:02:35 26 4
gpt4 key购买 nike

我实际上是从几个监控我每日卡路里摄入量的 Excel 文件中提取数据。我设法使用列表理解来生成日期。我尝试使用 merge 或 join 但它不起作用。ValueError:您正在尝试合并 object 和 float64 列。

date_list = ['2021-05-22','2021-05-24','2021-05-26','2021-05-27']
idx = pd.date_range(date_list[0], date_list[-1]) # To find missing dates
df_dates = pd.DataFrame(idx) # To convert list to DataFrame
df1_dates = pd.DataFrame(np.repeat(df_dates.values,2,axis=0)) # However, there is no column title and it is default at 0.

我还有另一组数据,包括我的卡路里摄入量和运动时间。

# These are Lists.
Time = [Morning, Afternoon, Morning, Afternoon, Morning, Afternoon, Morning, Afternoon]
Calories = [420,380,390,400,350,280,300,430]
Duration = [50,40,45,50,45,50,44,58]

我面临的问题是我不知道如何在使用 np.repeat 后为 df1_dates 数据框创建列标题(“日期”)。我想用“NaN”填充与缺失日期对应的其他列。

输出应该是这样的:

         Date       Time calories duration
0 22/5/2021 Morning 420 50
1 22/5/2021 Afternoon 380 40
2 23/5/2021 Morning Nan Nan
3 23/5/2021 Afternoon Nan Nan
4 24/5/2021 Morning 390 45
5 24/5/2021 Afternoon 400 50
6 25/5/2021 Morning Nan Nan
7 25/5/2021 Afternoon Nan Nan
8 26/5/2021 Morning 350 45
9 26/5/2021 Afternoon 280 50
10 27/5/2021 Morning 300 44
11 27/5/2021 Afternoon 430 58

最佳答案

使用现有数据构建您的数据框并使用缺失日期重新索引

# Input data
date_list = ['2021-05-22','2021-05-24','2021-05-26','2021-05-27']
calories = [420,380,390,400,350,280,300,430]
duration = [50,40,45,50,45,50,44,58]

# Dataframe with sparse index
idx = pd.MultiIndex.from_product([pd.to_datetime([d for d in date_list]),
["Morning", "Afternoon"]],
names=["Date", "Time"])
df = pd.DataFrame({'calories': calories, 'duration': duration}, index=idx)

# Dataframe with full index
idx1 = pd.MultiIndex.from_product([pd.date_range(date_list[0], date_list[-1]),
["Morning", "Afternoon"]],
names=["Date", "Time"])
df1 = df.reindex(idx1).reset_index()
>>> df1
Date Time calories duration
0 2021-05-22 Morning 420.0 50.0
1 2021-05-22 Afternoon 380.0 40.0
2 2021-05-23 Morning NaN NaN
3 2021-05-23 Afternoon NaN NaN
4 2021-05-24 Morning 390.0 45.0
5 2021-05-24 Afternoon 400.0 50.0
6 2021-05-25 Morning NaN NaN
7 2021-05-25 Afternoon NaN NaN
8 2021-05-26 Morning 350.0 45.0
9 2021-05-26 Afternoon 280.0 50.0
10 2021-05-27 Morning 300.0 44.0
11 2021-05-27 Afternoon 430.0 58.0

关于python - 用缺失日期填充其他列 Nan Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67748409/

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