在DateTIme上执行groupby后创建索引

2024-06-08 22:52:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下格式的数据(见下文)

enter image description here

接下来,我将执行重铸、分组和平均(参见代码),以降低数据维度

df_mod=pd.read_csv('wet_bulb_hr.csv')
#Mod Date
df_mod['wbt_date'] = pd.to_datetime(df_mod['wbt_date']) 

#Mod Time
df_mod['wbt_time'] = df_mod['wbt_time'].astype('int')
df_mod['wbt_date'] = df_mod['wbt_date'] + \
                     pd.to_timedelta(df_mod['wbt_time']-1, unit='h')

df_mod['wet_bulb_temperature'] = \
df_mod['wet_bulb_temperature'].astype('float')
df = df_mod
df = df.drop(['wbt_time','_id'], axis = 1)
#df_novel = df.mean()
df = df.groupby([df.wbt_date.dt.year,df.wbt_date.dt.month]).mean()

在写入输出文件后,我得到了如下输出

enter image description here

进一步调查,我能理解原因。我所有的处理都产生了形状为1的数据框,但我真正需要的是还要导出2个wbt_日期列。由于groupby函数的缘故,这种情况似乎不会发生

enter image description here

我的问题:如何生成索引并将groupby wbt_date列作为一个新的单列,以便输出为: enter image description here


Tags: csvto数据moddfdatetimepd
2条回答

您可以通过列表理解将多索引展平到YYYY-MM中的索引:

df = df.groupby([df.wbt_date.dt.year,df.wbt_date.dt.month]).mean()
df.index = [f'{y}-{m}' for y, m in df.index]
df = df.rename_axis('date').reset_index()

或按^{}使用月周期:

df = df.groupby([df.wbt_date.dt.to_period('m')).mean().reset_index()

试试这个

# rename exisiting index & on reset will get added as new column.

df.index.rename("wbt_year", inplace=True)
df.reset_index(inplace=True)
df['month'] = df['wbt_year'].astype(str) + "-" + df['wbt_date'].astype(str)

产出

>>> df['month']
0    2019-0
1    2018-1
2    2017-2

相关问题 更多 >