我有一个带有日期时间指数(例如降水量)的熊猫系列。我想计算这个降水时间序列的质心(由该值加权的日期时间的平均值)。我的问题是我不能将日期时间对象与浮点数相乘。 (不工作)的想法看起来像这样(输出应该是一个日期时间对象):
Map<Class, JAXBContext> map = new HashMap<>();
public JAXBContext getContext(Class clazz) {
if (map.get(clazz) == null) {
map.put(clazz, JAXBContext.newInstance(clazz));
}
return map.get(clazz);
}
答案 0 :(得分:1)
在计算产品之前尝试将datetime转换为纪元时间戳(并将最终结果转换回datetime)。我希望这会有所帮助。
import pandas as pd
import datetime as dt
df = pd.DataFrame({'P':[1.2,10.1,5.6,0,0,0,0,0,3,4,6,4,8,2,0,0,0,0,0,0,0,0,0,0]}, index=[dt.datetime(2012,1,1,h) for h in range(24)])
P_sum = df['P'].sum()
df["epoch"] = [float(t.strftime('%s')) for t in df.index]
prod = df["epoch"] * df['P'] / P_sum
mean_date = prod.mean()
print dt.datetime.fromtimestamp(mean_date).strftime('%Y-%m-%d %H:%M:%S')
更新:这可能就是您要找的内容:
import pandas as pd
import datetime as dt
df = pd.DataFrame({'P':[1.2,10.1,5.6,0,0,0,0,0,3,4,6,4,8,2,0,0,0,0,0,0,0,0,0,0]}, index=[dt.datetime(2012,1,1,h) for h in range(24)])
df["epoch"] = [float(t.strftime('%s')) for t in df.index]
mean_date = (df["epoch"] * df['P']).sum() / df['P'].sum()
print dt.datetime.fromtimestamp(mean_date).strftime('%Y-%m-%d %H:%M:%S')
输出:
2012-01-01 07:00:00
更新2:代码,具有更好的日期时间转换(相同的输出):
import pandas as pd
import datetime as dt
df = pd.DataFrame({'P':[1.2,10.1,5.6,0,0,0,0,0,3,4,6,4,8,2,0,0,0,0,0,0,0,0,0,0]}, index=[dt.datetime(2012,1,1,h) for h in range(24)]
df["epoch"] = df.index.astype('int64')//1e9
mean_date = (df["epoch"] * df['P']).sum() / df['P'].sum()
print dt.datetime.fromtimestamp(mean_date).strftime('%Y-%m-%d %H:%M:%S')