我有一个数据帧,看起来像这样
rootID parentID jobID time counter
0 A B D 2019-01-30 14:33:21.339469 0
1 E F G 2019-01-30 14:33:21.812381 0
2 A C D 2019-01-30 15:33:21.812381 0
3 E B F 2019-01-30 15:33:21.812381 0
4 E F G 2019-01-30 16:33:21.812381 0
我会喂活的数据,该数据是rootID字符串,字符串的parentID,作业ID字符串和日期。
我要检查,如果新检索rootID和组合的parentID在数据帧已经存在。所以,如果我找回rootID =“A”和==的parentID“B”,作业ID ==“T”我要访问的数据框的第一行。然后我想删除该行并追加新的信息和增量更新计数器。
IF rootID and parentID exist in the same row in dataframe.
delete row and append new data with updated jobID and incremented counter.
数据框应该像
rootID parentID jobID time counter
0 E F G 2019-01-30 14:33:21.812381 0
1 A C D 2019-01-30 15:33:21.812381 0
2 E B F 2019-01-30 15:33:21.812381 0
3 E F G 2019-01-30 16:33:21.812381 0
4 A B T 2019-01-30 17:33:21.339469 1
任何人有任何想法怎么可以这样做?
我会
root_id, parent_id, job_id = get_ids() # e.g. ('A', 'B', 'T')
cond = df.rootID.eq(root_id) & df.parentID.eq(parent_id) & df.jobID.eq(job_id)
df.loc[cond, ['time', 'counter']] = datetime.datetime.now(), df.loc[cond, 'counter']+1
这将更新您的数据帧in_place
。我不会重新排序数据框所有的时间,除非它是绝对必要的。如果你可以,例如,重新排序,一旦一天,你可以
df.sort_values(by='time') #.reset_index(drop=True), if needed
定期。但是,如果你非得每个新数据来自时间来改变行,那么,假设你有唯一的ID,
df = pd.concat([df[df[cond].index.item()+1:], df[cond]])
我想,你可以通过你的翻译例如得到一个相当接近的解决方案:
for index, row in df.iterrows():
if row['rootID'] == rootID and row['parentID'] == parentID:
df.drop(df.iloc[index])
row['time'] = datetime.datetime.now()
row['counter'] += 1
df = df.concat(row)
没有循环:
selected_row = df[(df['rootId'] == rootID) & (df['parentID'] == parentID)])
df.drop(selected_row)
selected_row['time'] = datetime.datetime.now()
selected_row['counter'] += 1
df = df.concat(selected_row)
这个假设你只有一排匹配rootID和组合的parentID您正在寻找。