[英]Calculate the average date every x rows
之前我發布了一個問題來計算每 10 行的平均值。 它在 Zero 的編碼中取得了成功。 通過pandas計算每列每10個單元格的平均值
但是計算時間date的平均值有錯誤
import numpy as np
location2='C:\\Users\\Poon\\Downloads\\20211014_SBS_BEMS\\20211014_SBS_BEMS\\Test1044.csv'
csvfiles2=glob.glob(location2)
df3=pd.DataFrame()
for file_new_2 in csvfiles2:
df3=pd.read_csv(file_new_2)
df4=pd.concat([pd.to_datetime(df3.iloc[:,0]), df3.iloc[:, 1:].apply(pd.to_numeric)], axis = 1)
df4.dropna(inplace = True)
df4= df4.groupby(np.arange(len(df4))//10).mean()
print(df4)
錯誤代碼是
Unable to parse string "2019-05-19 00:00:00" at position 0
我想表揚 pd.to_datetime 不能總結然后除以 10?
這是我的 excel 中的一些數據,但總共有 100k 行。
19/5/2019 0:00 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:01 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:02 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:03 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:04 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:05 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:06 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:07 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:08 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:09 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:10 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:11 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:12 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:13 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:14 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:15 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:16 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:17 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:18 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:19 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:20 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:21 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:22 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:23 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:24 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:25 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:26 8840 20 237 64.93 82.35 16.15 46.88
19/5/2019 0:27 8840 20 237 64.93 82.35 16.15 46.88
假設在提供的示例中為第0
列,將時間戳轉換為 integer,按索引的下限除以 10 分組並聚合:
import numpy as np
out = pd.to_datetime(pd.to_datetime(df[0])
.astype(np.int64)
.groupby(df.index//10)
.mean())
Output:
0 2019-05-19 00:04:30
1 2019-05-19 00:14:30
2 2019-05-19 00:23:30
Name: 0, dtype: datetime64[ns]
您可以使用resample
:
>>> (df4.assign(**{'dt': pd.to_datetime(df.iloc[:, 0])})[1:]
.resample('10T', on='dt').mean())
1 2 4 5 6
dt
2019-05-19 00:00:00 8840.0 20.0 82.35 16.15 46.88
2019-05-19 00:10:00 8840.0 20.0 82.35 16.15 46.88
2019-05-19 00:20:00 8840.0 20.0 82.35 16.15 46.88
如果您的列有名稱,它會更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.