我有一個問題:我想用 Pandas 對時間資料值求和。我有 15 分鐘的資料,我想對一小時的值求和。
例如:我的資料
| 指數 | 日期 | 時間 | 價值 |
|---|---|---|---|
| 0 | 11.06.2021 | 04:00 | 1125.6 |
| 1 | 11.06.2021 | 04:15 | 5622.2 |
| 2 | 11.06.2021 | 04:30 | 3222.6 |
| 3 | 11.06.2021 | 04:45 | 2666.7 |
| 4 | 11.06.2021 | 05:00 | 4657.2 |
| 5 | 11.06.2021 | 05:15 | 2946.8 |
| 6 | 11.06.2021 | 05:30 | 3255.4 |
| 7 | 11.06.2021 | 05:45 | ... |
| 8 | 11.06.2021 | 06:00 | ... |
| 9 | 11.06.2021 | 06:15 | ... |
| 10 | 11.06.2021 | 06:30 | ... |
| ... | ... | ... | ... |
我希望有:
| 指數 | 日期 | 時間 | 價值 |
|---|---|---|---|
| 0 | 11.06.2021 | 4:00 | 從4:00到4:45的額 |
| 1 | 11.06.2021 | 5:00 | ... |
| 2 | 11.06.2021 | 6:00 | ... |
該資料稱為test:
我的解決方案:
result = []
result1 = []
counter11 = 0
for index, row in test.iterrows():
counter11 = 1
print(counter11)
result1 = test.values[index]
result = result1
if counter11 == 3:
result.add(result.values)
result = 0
counter = 0
test["sum"] = result
如果有人可以幫助我,我會很高興。謝謝你。
uj5u.com熱心網友回復:
使用:
- 連接
Date和Time列 pandas.to_datetime轉換為日期時間set_index到日期時間resample用了幾個小時sum用min_count=1o 區分該期間何時沒有值。
import pandas as pd
# creating the dataframe
import io
data = """
Index,Date,Time,Value
0,11.06.2021,04:00,1125.6
1,11.06.2021,04:15,5622.2
2,11.06.2021,04:30,3222.6
3,11.06.2021,04:45,2666.7
4,11.06.2021,05:00,4657.2
5,11.06.2021,05:15,2946.8
6,11.06.2021,05:30,3255.4
7,11.06.2021,07:30,1111.1
"""
df = pd.read_csv(io.StringIO(data), sep=',', usecols=['Date', 'Time', 'Value'])
# processing
df['Datetime']= pd.to_datetime(df['Date'] ' ' df['Time'])
df.drop(['Date', 'Time'], axis=1, inplace= True)
df.set_index('Datetime', inplace= True)
print(df.resample('H').sum(min_count=1))
# output
Value
Datetime
2021-11-06 04:00:00 12637.1
2021-11-06 05:00:00 10859.4
2021-11-06 06:00:00 NaN
2021-11-06 07:00:00 1111.1
uj5u.com熱心網友回復:
如果您使用的是熊貓,我想提出兩個建議。
首先,您應該使用 pandas 內置日期時間,您可以在檔案中找到有關它的所有內容:https ://pandas.pydata.org/docs/user_guide/timeseries.html?highlight=datetime
這將使您在處理日期和時間時更輕松。您可以使用 datetime 物件來創建和索引,如下面的代碼示例所示。
第二個建議是,一旦您使用了 pandas datetime,您實際上可以使用其他內置函式,例如重采樣。這將根據您提供給函式的一些邏輯對資料框中的資料進行“分組”,例如按小時重新采樣。然后,您可以將函式應用于重新采樣的資料,例如 sum()。
import pandas as pd
#This is just for making this example, you will not need numpy
import numpy as np
"This creates a datetime index"
idx = pd.date_range("2018-01-01", periods=70, freq="T")
"Creating a sample dataframe to work with"
df = pd.DataFrame(np.repeat(1,70), index=idx, columns= ["Data"])
"""
This is what you are trying to do:
Resampling or 'grouping' the data by hours (in this case) and sums all
values for each hour.
"""
df.resample("H").sum()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383587.html
