![](/img/trans.png)
[英]converting daily stock data to weekly-based via pandas in Python
[英]Daily python data to weekly via pandas
我想使用显示每日数据的 CSV 并创建一个包含每周视图中相同数据的新工作表。
目前我有:
#import required libraries
import pandas as pd
from datetime import datetime
#read the daily data file
looker_data = pd.read_csv("jan21_looker_upload.csv")
#convert date column into datetime object
looker_data['Date'] = looker_data['Date'].astype('datetime64[ns]')
#convert daily data to weekly
weekly_data = looker_data.groupby("URL").resample('W-Mon', label='right', closed='right', on='Date').sum().reset_index().sort_values(by='Date')
##Export in Excel
weekly_data.to_excel("jan21-looker.xlsx")
该代码有效,但删除了我想保留在新视图中的特定数据点。 作为参考,现有的 CSV 看起来像这样:
Date | URL | Sessions | Conversions
1/14/21 | example.com/ | 110333. | 330
但是当我运行代码时,我得到:
URL | Date | Conversions
example.com/ | 1/14/21 | 330
有什么我遗漏的东西可以帮助我将 output 包含在每周视图中的所有数据? 感谢所有帮助!
loc[]
将列顺序放回原位d = pd.date_range(dt.date(2021,1,20), "today")
df = pd.DataFrame({
"Date":d,
"URL":np.random.choice(["example.com/","google.com/","bigbank.com/"],len(d)),
"Sessions": np.random.randint(3000, 300000, len(d)),
"Conversations": np.random.randint(200, 500, len(d))
})
dfw = (df.groupby("URL").resample('W-Mon', label='right', closed='right', on='Date').sum()
# cleanup - index as columns, order or row & columns
.reset_index().sort_values("Date").loc[:,df.columns]
)
日期 | URL | 会话 | 对话 | |
---|---|---|---|---|
0 | 2021-01-25 00:00:00 | bigbank.com/ | 187643 | 226 |
4 | 2021-01-25 00:00:00 | example.com/ | 454543 | 966 |
7 | 2021-01-25 00:00:00 | google.com/ | 143307 | 574 |
1 | 2021-02-01 00:00:00 | bigbank.com/ | 335614 | 904 |
5 | 2021-02-01 00:00:00 | example.com/ | 260055 | 623 |
8 | 2021-02-01 00:00:00 | google.com/ | 396096 | 866 |
2 | 2021-02-08 00:00:00 | bigbank.com/ | 743231 | 1143 |
6 | 2021-02-08 00:00:00 | example.com/ | 562073 | 1206 |
9 | 2021-02-08 00:00:00 | google.com/ | 229929 | 472 |
3 | 2021-02-15 00:00:00 | bigbank.com/ | 327898 | 747 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.