[英]How can I keep the rows of a pandas data frame that match a particular condition using value_counts() on multiple columns
[英]In pandas, how to check if two strings match multiple columns in any of the rows in existing data frame and delete it
我有一个看起来像这样的数据框
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字符串,jobID字符串和一个日期。
我想检查新检索到的rootID和parentID组合是否已存在于数据框中。 因此,如果我检索rootID =“ A”和parentID ==“ B”,jobID ==“ 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
。 除非绝对需要,否则我不会一直对Dataframe进行重新排序。 例如,如果您每天可以重新排序一次,则可以
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组合匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.