Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将熊猫的每日数据与每月数据相结合?_Python_Pandas - Fatal编程技术网

Python 如何将熊猫的每日数据与每月数据相结合?

Python 如何将熊猫的每日数据与每月数据相结合?,python,pandas,Python,Pandas,我有每日数据,也有每月数据。我想通过每月数字对每日数据进行标准化,例如,2017年前31天都被另一个数据集中对应于2017年1月的数字除以 import pandas as pd import datetime as dt N=100 start=dt.datetime(2017,1,1) df_daily=pd.DataFrame({"a":range(N)}, index=pd.date_range(start, start+dt.timedelta(N-1))) df_monthly=

我有每日数据,也有每月数据。我想通过每月数字对每日数据进行标准化,例如,2017年前31天都被另一个数据集中对应于2017年1月的数字除以

import pandas as pd
import datetime as dt

N=100
start=dt.datetime(2017,1,1)
df_daily=pd.DataFrame({"a":range(N)}, index=pd.date_range(start, start+dt.timedelta(N-1)))

df_monthly=pd.Series([1, 2, 3], index=pd.PeriodIndex(["2017-1", "2017-2", "2017-3"], freq="M"))

df_daily["a"] / df_monthly # ???
我希望时间序列数据能够以一对多的方式对齐,并执行所需的操作,但是我得到了很多NaN

如何在Pandas中正确地进行一对多数据对齐


我可能还希望合并数据,在这种情况下,我希望每月数据在一个月内复制值。

您可以从索引的月份创建一个临时键,然后合并键上的两个数据帧,即

df_monthly = df_monthly.to_frame().assign(key=df_monthly.index.month)
df_daily = df_daily.assign(key=df_daily.index.month)

df_new = df_daily.merge(df_monthly,how='left').set_index(df_daily.index).drop('key',1)

            a    0
2017-01-01  0  1.0
2017-01-02  1  1.0
2017-01-03  2  1.0
2017-01-04  3  1.0
2017-01-05  4  1.0
对于分区,您只需执行以下操作:

df_new['b'] = df_new['a'] / df_new[0]

您可以从索引的月份创建一个临时键,然后合并键上的两个数据帧,即

df_monthly = df_monthly.to_frame().assign(key=df_monthly.index.month)
df_daily = df_daily.assign(key=df_daily.index.month)

df_new = df_daily.merge(df_monthly,how='left').set_index(df_daily.index).drop('key',1)

            a    0
2017-01-01  0  1.0
2017-01-02  1  1.0
2017-01-03  2  1.0
2017-01-04  3  1.0
2017-01-05  4  1.0
对于分区,您只需执行以下操作:

df_new['b'] = df_new['a'] / df_new[0]

您可以使用
to_period('M')
提取信息,然后使用
map

df_daily["month"] = df_daily.index.to_period('M')
df_daily['a'] / df_daily["month"].map(df_monthly)
无需创建
month
列,即可使用

df_daily['a'] / df_daily.index.to_period('M').to_series().map(df_monthly)

您可以使用
to_period('M')
提取信息,然后使用
map

df_daily["month"] = df_daily.index.to_period('M')
df_daily['a'] / df_daily["month"].map(df_monthly)
无需创建
month
列,即可使用

df_daily['a'] / df_daily.index.to_period('M').to_series().map(df_monthly)