[英]Incrementally add time to column in dataframe based on first value of the column
我有一個場景,我必須增加 dataframe 中列的時間戳。
dataframe 由一個具有一組相同區域 ID 的列和一個“waterDuration”列組成。
我想將此持續時間連續添加到每種區域類型的第一行中給出的時間戳中,並逐步更新每個區域 ID 的行的 rest。
這就是我的 dataframe 的樣子。
給定每個 areaId 的第一個時間戳,我想將其旁邊給出的任何持續時間添加到初始值,並為 rest 更新和遞增,例如:-
這些是我的 dataframe 的所有列:-
scheduleId int64
scheduleName object
areaId object
deviceId object
stationDeviceId object
evStatus object
waterDuration object
noOfCyles object
startTime1 object
startTime2 object
startTime3 object
startTime4 object
waterPlanning object
lastUpdatedTime object
dtype: object
我希望 df 中的所有這些列及其值以及 startTime1 中的更新值保持不變。
waterDuration 的值可以改變,所以我不想直接在解決方案中使用它。 任何幫助都會很棒
所以這是你的 dataframe:
data = {
"areaID": [125659657, 125659657, 125659657, 125659657, 9876913, 9876913, 9876913, 9876913],
"waterDuration": [15, 15, 15, 15, 10, 10, 10, 10],
"startTime1": ["00:04:00", "00:00:00", "00:00:00", "00:00:00", "00:34:00", "00:00:00", "00:00:00", "00:00:00"]
}
df = pd.DataFrame(data)
為了獲得您想要的 output,創建一個 function 以應用於 dataframe:
def add_from_last_row(row):
# If first row, nothing to do
# row.name corresponds to the DataFrame index
if row.name == 0:
return row.startTime1
# If prev. row is not the same area, do nothing
if row.areaID != df.loc[row.name-1, 'areaID']:
return row.startTime1
# Get the min index in order to get the original startTime
min_index = df[df.areaID == row.areaID].index.min()
# Here we get the original startTime, cast to datetime
default_time = pd.to_datetime(df.loc[min_index, 'startTime1'], format="%H:%M:%S")
# Sum all durations from min_index+1 to current row index
seconds_to_add = df.loc[min_index+1:row.name, 'waterDuration'].sum()
# Calculate the offset in seconds
offset = pd.DateOffset(seconds=int(seconds_to_add))
# return the last 8 character ie. hh:mm:ss
# otherwise it would be YYYY-MM-DD hh:mm:ss
return str(default_time + offset)[-8:]
然后應用它:
df.apply(lambda x: add_from_last_row(x), axis=1)
結果:
0 00:04:00
1 00:04:15
2 00:04:30
3 00:04:45
4 00:34:00
5 00:34:10
6 00:34:20
7 00:34:30
dtype: object
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.